EF6 CF中的外键问题

时间:2013-12-19 03:36:17

标签: c# entity-framework ef-code-first entity-framework-6 ef-fluent-api

对于代码优先考虑成为EF的菜鸟,请原谅。我的问题是我不想将外键属性添加到模型中,根据MSDN,使用流畅的API没有问题,但是我无法弄清楚当前情况的正确用法。看起来很简单:

public class Package
{
    public Package()
    {
        Users = new Collection<User>();
    }

    public Int32 Id {get; set;}
    public String Name {get; set;}
    public virtual User Creator {get; set;}

    public virtual ICollection<User> Users {get; set;}
}

public class User
{
    public Int32 Id {get; set;}
    public String Name {get; set;}
}

public class PackageContext : DbContext
{
    public DbSet<Package> Packages {get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Package>().HasRequired(p => p.Creator).WithMany();
        modelBuilder.Entity<Package>().HasMany(p => p.Users).WithRequired().Map(c => c.MapKey("PackageId"));

        base.OnModelCreating(modelBuilder);
    }
}

我尝试了许多不同的流畅组合但没有正常工作。我得到的最常见的例外是:

System.Data.Entity.Infrastructure.DbUpdateException:保存未公开其关系的外键属性的实体时发生错误。 EntityEntries属性将返回null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。

有人可以帮我找出创建模型时需要进行的正确流畅的电话吗?

1 个答案:

答案 0 :(得分:1)

你应该使用这个:

public class Package
{
    public Int32 Id {get; set;}
    public String Name {get; set;}
    public Int32 UserId {get; set;}

    public virtual User Creator {get; set;}    
}

public class User
{
    public User()
    {
        Packages = new Collection<Package>();
     }

    public Int32 Id {get; set;}
    public String Name {get; set;}

    public virtual ICollection<Package> Packages {get; set;}
}

public class PackageContext : DbContext
{
    public DbSet<Package> Packages {get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Package>().HasRequired(current => current.Creator)
            .WithMany(c=>c.Packages)
            .HasForeignKey(c=>c.UserId)
            .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
    }
}