MVC5代码优先一对一关系错误

时间:2016-02-18 09:26:25

标签: c# entity-framework relationship one-to-one

我试图为MVC5 codefirst做一对一的关系。 I've looked this page并做了完全相同的事情,但我发现了错误。

这是我的课程和背景:

产品:

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    /// <summary>
    /// Display order
    /// </summary>
    public int Order { get; set; }
    public string TitleBackgroundColor { get; set; }
    public virtual TblClass TblClass { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
    public virtual ICollection<Price> Prices { get; set; }
    public virtual ICollection<ProductFeature> ProductFeatures { get; set; }
}

TblClass:

 public class TblClass
{
    [Key, ForeignKey("Product")]
    public int ProductId { get; set; }
    public string ClassName { get; set; }
    public virtual ICollection<Permission> Permissions { get; set; }
    public virtual Product Product { get; set; }
    public int ClassOrder { get; set; }
}

的DbContext:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Role>()
            .HasMany<UserProfile>(r => r.UserProfiles)
            .WithMany(u => u.Roles)
            .Map(m =>
            {
                m.ToTable("webpages_UsersInRoles");
                m.MapLeftKey("RoleId");
                m.MapRightKey("UserId");
            });

        modelBuilder.Entity<TblClass>()
            .HasKey(c => c.ProductId);

        modelBuilder.Entity<Product>()
        .HasOptional(f => f.TblClass)
        .WithRequired(s => s.Product)
        .Map(t => t.MapKey("ProductId"));
    }

当我尝试运行更新数据库-verbose&#39;我有这个错误:

  

导航属性&#39;产品&#39;声明在类型&#39; YazililarGaranti.Domain.Entities.TblClass&#39;已配置有冲突的外键。

1 个答案:

答案 0 :(得分:0)

在建立1:1关系时,您不必使用.Map(t => t.MapKey("ProductId")。这应该有效:

public class Product
{
    public int ProductId { get; set; }
    //... other properties
    public virtual TblClass TblClass { get; set; }
    //... other properties
}

public class TblClass
{
    //[Key, ForeignKey("Product")] <-- remove these attributes
    public int ProductId { get; set; }
    public string ClassName { get; set; }
    //.. other properties
    public virtual Product Product { get; set; }
    public int ClassOrder { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //other mappings

    modelBuilder.Entity<TblClass>()
        .HasKey(c => c.ProductId); 

    modelBuilder.Entity<Product>()
        .HasKey(c => c.ProductId); //consider to use database generated option

    //modelBuilder.Entity<Product>().Property(t => t.ProductId) 
        //.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    modelBuilder.Entity<Product>()
        .HasOptional(f => f.TblClass)
        .WithRequired(s => s.Product);
}

希望这有帮助!