EF: 1:1 relationship independent association

北慕城南 提交于 2019-12-13 17:45:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!