make both models aware of each other with a one-to-one relationship in asp.net entity framework - asp.net

I am unable to get the one to one relationship with EF to work properly. I've scored blogs, SO, and msdn docs, but nothing I do seems to work.
I have two models, a Class and an Exam that look like the following:
[Table("classes")]
public class Class
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(255), Required]
public string Title { get; set; }
public virtual Exam Exam { get; set; }
}
[Table("exams")]
public class Exam
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:h:mm tt}")]
public DateTime? Time { get; set; }
public int ClassId { get; set; }
public virtual Class Class { get; set; }
}
I want to be able to access the exam from the Class and the Class from the Exam, but no matter what I do, I find some error.
Trying to create/run migrations I get the following.
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
If I add this to my context:
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<Exam>()
.HasRequired(e => e.Class)
.WithOptional(c => c.Exam);
}
I get the following error:
System.Data.Entity.Infrastructure.DbUpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected. ---> System.Data.UpdateException: Entities in 'BenchContext.Exams' participate in the 'Class_Exam' relationship. 0 related 'Class_Exam_Source' were found. 1 'Class_Exam_Source' is expected.
I'm not sure how to tell the fluent api how to correctly foreign key between the two models and nothing I do seems to affect it.
What am I missing?

You are trying to build one-to-one relation through ClassId property in Exam class. That requires ClassId to be unique (= unique constraint) but unique constraint are not supported by EF yet.
The only way EF currently supports real one-to-one relation is by sharing primary key:
[Table("classes")]
public class Class
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(255), Required]
public string Title { get; set; }
public virtual Exam Exam { get; set; }
}
[Table("exams")]
public class Exam
{
[Key, ForeignKey("Class")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:h:mm tt}")]
public DateTime? Time { get; set; }
public virtual Class Class { get; set; }
}
The Id in Exams table is both PK and FK to Classes table. It cannot have autogenerated value. While this is one-to-one relation it still has 1 - 0..1 multiplicity (Class can exist without Exam but Exam must have Class).

Related

Entity Framework Core - optional foreign key

I am creating a web api that needs to return details about vehicles. The first part works fine, just returning data from my vehicles table. Now I have another table which may or may not contain additional data about vehicles in the first table. So when I get vehicle data, I want all of the vehicle data, and any additional data from the second table if it exists, like a left join in SQL.
Here are my classes (very much abridged for readability):
public class Vehicle
{
[Key]
[Required]
public string registrationNo { get; set; }
public string capacity{ get; set; }
public string maxGross{ get; set; }
}
public class VehicleDvlaDetail
{
[ForeignKey("Vehicle")]
public string? registrationNumber { get; set; }
public int? co2Emissions { get; set; }
}
And in my context class OnModelCreating I have (again, very abridged):
modelBuilder.Entity<Vehicle>(entity =>
{
entity.HasOne(dvlaRec => dvlaRec.dvlaDetail).WithMany().HasForeignKey(dvla => dvla.registrationNo);
});
This works fine when there is an associated record in the DVLA table, but that isn't always the case. I need to keep them as separate entities as my API will be required to return details from the DVLA table separately as well. Is there any way to create an optional foreign key, as clearly, what I am doing is wrong.
Friendly advice:
Primary key as a string is not a good practice because of performance issues when data table has lots of data in it.
It would be better if you create your model like this:
public class Vehicle
{
public long Id { get; set; }
public string RegistrationNo { get; set; }
public string Capacity { get; set; }
public string MaxGross { get; set; }
public List<VehicleDvlaDetail> VehicleDvlaDetails { get; set; }
}
public class VehicleDvlaDetail
{
public long? VehicleId { get; set; }
public int? Co2Emissions { get; set; }
public Vehicle Vehicle { get; set; }
}
Vehicle and VehicleDvlaDetail are now connected without additional code in OnModelCreating method and it is possible to fetch vehicles with details like this (this is assuming you have named properties in dbcontext Vehicles and VehicleDvlaDetails):
_dbContext.Vehicles.Include(x => x.VehicleDvlaDetails).ToList();
Also as foreign key VehicleId is nullable - this allows for vehicles not to have any dvla details.
Wow. I spent about 3 hours looking for the answer, just posted the question and came across this:
Create an optional foreign key using the fluid-API for Entity Framework 7
So simple...

zero to one relationship entity framework

I am trying to create a zero to one relationship with code first entity framework. With the sample code below, I am getting error message:
Unable to determine the principal end of an association between the types 'CompanyView' and 'MemberView'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
With this error, I have tried added in a configuration to fix this.
modelBuilder.Entity<CompanyView>().HasOptional(x => x.MemberView).WithOptionalPrincipal(x => x.CompanyView);
Which ended up with another error message.
CompanyView_MemberView_Target: : Multiplicity is not valid in Role 'CompanyView_MemberView_Target' in relationship 'CompanyView_MemberView'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Anyone have any idea on what is going one here?
Thanks.
public class CompanyView
{
[Key]
public Guid Id { get; private set; }
public Guid? MemberId { get; private set; }
[ForeignKey("MemberId")]
public MemberView MemberView { get; private set; }
}
public class MemberView
{
[Key]
public Guid Id { get; private set; }
public Guid? CompanyId { get; private set; }
[ForeignKey("CompanyId")]
public CompanyView CompanyView { get; private set; }
}
The end result I would expected is as below:
A MemberView can have 0 or 1 CompanyView, each CompanyView can have 0 to 1 MemberView.
Relationship as you specified is unusual (one or zero at both directions). You try to create foreign keys at both tables, as the result you have insoluble loop. You can easily create relation one or zero in case when one entity is principal and one is dependent. You can try to simulate desired relation via many to many relationship. Also you can to not annotate fields with foreign key attributes, as the result you will not have some benefits, but you will be able to flexible manipulate relationships manually on your own. At the end, I demonstrate relation where, for example, MemberView is dependent table:
public class CompanyView
{
[Key]
public Guid Id { get; private set; }
public MemberView MemberView { get; private set; }
}
public class MemberView
{
[Key, ForeignKey("CompanyView")]
public Guid CompanyId { get; private set; }
public CompanyView CompanyView { get; private set; }
}

Tree structure with reference to root in Entity Framework

I'm trying to model a tree structure for orders in Entity Framework. Right now I've go the following:
public class ProjectModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CustomerId { get; set; }
public virtual List<ProjectNode> Nodes { get; set; }
}
public class ProjectNode
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Path { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual List<ProjectNode> Children { get; set; }
}
What I need to be able to do is get a reference to the root ProjectModel at any level of ProjectNode in order to authorize a given user actually having permission to view and change the project which contains the ProjectNode.
public class ProjectNode {
public int ProjectId { get; set; } //<-- this
...
public class ProjectModel {
[Key]
public int Id { get; set; } //<-- containing the value of this
}
My question is whether its possible to have a theoretical ProjectId property populated at every level of the tree structure, or if I need to set it manually.
I had something working that at first blush appeared to allow this functionality, but upon further investigation only populated the ProjectId for ProjectNodes contained in the ProjectModel's Nodes property.
It seems to me like it would be super inefficient to recurse backwards through the structure to get to the root.
Credit due to #TestWell for this answer -
Apparently, all I needed to do for EF to automatically populate the ProjectId property on the ProjectNode was to change the name of the Id property in ProjectModel to ProjectId.
Unfortunately, this doesn't appear to work if I add a CustomerId property to the ProjectNode that I would like automatically populated from the property of the same name on the node's root ProjectModel, which I realized is the more efficient solution to what I'm trying to do.

Is it OK to declare a DBSet in the context for both a base table and a derived table?

I have a SalesOrder table which inherits from a SalesDocument table using Table Per Type Inheritance
The ( simplified) table classes are;
[Table("SalesDocumentHeaders")]
public abstract class SalesDocumentHeader
{
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
[Required]
public int CreatedByUserId { get; set; }
[Required]
public virtual DateTime? DocumentDate { get; set; }
[Required]
public String ReferenceNumber { get; set; }
}
[Table("SalesOrders")]
public class SalesOrder : SalesDocumentHeader
{
[Required]
public String CustomerOrderNumber { get; set; }
public DateTime? DeliverBy { get; set; }
public virtual SortableBindingList<SalesOrderLine> Lines { get; set; }
}
The context contains
public DbSet<SalesOrder> SalesOrders { get; set; }
public DbSet<SalesDocumentHeader> SalesDocumentHeaders { get; set; }
It doesn't strictly need the SalesOrders DBSet, since SalesOrder inherits from SalesDocumentHeader however I find it convenient.
It seems to work OK, but I am worried that there are 2 ways of reaching the same record , am I doing something wrong?
Usually you only need to keep the DBSet for the base table. This helps when you have multiple derived tables (call them A and B) and you need to decide the actual type dynamically.
For example if you have another entity which references type A or B (like a user can have different types of contact information), you can reference the base table and EF will resolve the correct concrete type at runtime. Though of course this adds some extra casting code.

EF5 Code First The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I found several questions on here relating to this but I'm not quite there. I'm trying to add a second UserProfile property to the already existing CourseRegistration class. When I try to perform the migration I get "The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.CourseRegistrations_dbo.UserProfile_InstructorId"
I thought I could solve it with some fluent configuration but it had no effect. Based on what I've read I think the issue is that there is existing data that won't allow this.
Question 1: I don't completely understand what it's complaining about and would like to understand it better if anyone could shed some light.
Question 2: Is there any workaround other than dropping the table or removing the data? I don't mind doing that this time, but I'm sure there are situations where that's not an option.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class CourseRegistration
{
[Key]
public int RegistrationId { get; set; }
public int UserId { get; set; }
public int? InstructorId { get; set; }
public virtual UserProfile user { get; set; }
public virtual UserProfile Instructor { get; set; }
}
Thanks,
joel
See this, and try this:
public class CourseRegistration
{
[Key]
public int RegistrationId { get; set; }
public virtual UserProfile user { get; set; }
[ForeignKey("InstructorId")]
public virtual UserProfile Instructor { get; set; }
}

Resources