问题
I'm trying to create a simple 1:1 relationship with EF code first.
Example: A person always owns a single car and the car always belongs to a single person.
Person:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public Car Car { get; set; }
}
// PersonEntityTypeConfiguration
HasKey(k => k.Id);
Property(p => p.Name).IsOptional();
HasRequired(n => n.Car).WithRequiredPrincipal().WillCascadeOnDelete(true);
Car:
public class Car
{
public Guid Id { get; set; }
public string SerialNumber { get; set; }
}
// CarEntityTypeConfiguration
HasKey(k => k.Id);
Property(p => p.SerialNumber).IsOptional();
This created the following migration script:
// Up
CreateTable(
"dbo.People",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Cars",
c => new
{
Id = c.Guid(nullable: false),
SerialNumber = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.People", t => t.Id, cascadeDelete: true)
.Index(t => t.Id);
I expected EF to generate a foreign key like:
CreateTable(
"dbo.Cars",
c => new
{
Id = c.Guid(nullable: false),
SerialNumber = c.String(),
Person_Id = c.Guid()
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.People", t => t.Person_Id, cascadeDelete: true)
.Index(t => t.Id);
Why EF didn't create a foreign key like that?
How do I tell EF to generate the script that I expect?
回答1:
If you want Car
to have a foreign key to Person
this is not a 1:1
association but 1:n
(because n
cars can refer to the same person).
What you see here is EF's way to enforce a 1:1
association: the primary key of the principal entity (Person
) is copied to the primary key of the dependent entity (Car
). The latter is also a foreign key to the principal.
来源:https://stackoverflow.com/questions/27381194/ef-11-relationship-independent-association