相同实体上的一对多和一对一

时间:2018-05-08 15:40:12

标签: entity-framework-6 foreign-keys

商业案例

我们有一件可以订购几种不同颜色的衬衫:Yello;白色;橙子;蓝色;绿色;红色; 但是,只能选择一种颜色作为衬衫的默认颜色。

实施

这是我到目前为止所做的:

public class Shirt
{
    public int Id { get; set; }

    public string Sku { get; set; }
    public string Description { get; set; }

    public Color DefaultColor { get; set; }

    public ICollection<Color> AvailableColors { get; set; }
}

public class Color
{
    public int Id { get; set; }

    public string ColorCode { get; set; }
    public string Name { get; set; }
    public string HexCode { get; set; }

    public int ShirtId { get; set; }
    public virtual Shirt Shirt { get; set; }
}


public class ShirtContext : DbContext
{
    public ShirtContext() : base("name=DefaultConnection") { }
    public DbSet<Shirt> Shirts { get; set; }
    public DbSet<Color> Colors { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Shirt>()
            .HasRequired(c => c.DefaultColor)
            .WithRequiredDependent(c => c.Shirt);

        modelBuilder.Entity<Color>()
            .HasRequired(c => c.Shirt)
            .WithMany(o => o.AvailableColors)
            .WillCascadeOnDelete();

        base.OnModelCreating(modelBuilder);
    }
}

问题

System.Data.Entity.Core.MetadataException: 'Schema specified is not valid. Errors: The relationship 'ShirtPortal.Data.Color_Shirt' was not loaded because the type 'ShirtPortal.Data.Color' is not available.'

我是否可以帮助在我的实体中设置外键关系以匹配我的业务案例?

0 个答案:

没有答案