实体框架4.1代码优先外键ID [英] Entity Framework 4.1 Code First Foreign Key Id's

查看:108
本文介绍了实体框架4.1代码优先外键ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体被一对多引用.当实体框架创建表时,它将创建两个外键,一个用于我通过fluent接口指定的键,另一个用于ICollection.如何摆脱重复的外键?

I have two entities referenced one to many. When entity framework created the table it creates two foreign keys, one for the key I have specified with the fluent interface and the other for the ICollection. How do I get rid of the duplicate foreign key?

public class Person
{
    public long RecordId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }

    public long DepartmentId { get; set; }
    public virtual Department Department { get; set; }
}

public class Department
{
    public long RecordId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Person> People { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasRequired(p => p.Department)
        .WithMany()
        .HasForeignKey(p => p.DepartmentId)
        .WillCascadeOnDelete(false);
}

谢谢!

推荐答案

您必须明确指定关联的多端:

You must specify the many-end of the association explicitely:

modelBuilder.Entity<Person>()
    .HasRequired(p => p.Department)
    .WithMany(d => d.People)
    .HasForeignKey(p => p.DepartmentId)
    .WillCascadeOnDelete(false);

否则,EF将假定存在两种关联:不会在Department中用外键DepartmentIdPerson类中的外键DepartmentId和导航属性Department公开,就像您在Fluent代码中定义的那样-另一个关联属于公开的导航属性People,但另一个关联的未公开端位于Person中,并且由EF自动创建外键.那是您在数据库中看到的另一个键.

Otherwise EF will assume that there are two associations: One which is not exposed in Department with the foreign key DepartmentId and navigation property Department in the Person class as you have defined in the Fluent code - and another association which belongs to the exposed navigation property People but with another not exposed end in Person and a foreign key automatically created by EF. That's the other key you see in the database.

这篇关于实体框架4.1代码优先外键ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆