literal or constant as part of composite key in EF code first

左心房为你撑大大i 提交于 2019-12-05 05:43:08

What you want is impossible for EF. ArCode has a composite key, so any association to it will have to use two Properties. That means that in Invoice you'd need four properties (two pairs) to refer to the two ArCode objects. But two of these properties (those for CodeType) are not backed up by columns in the database, so EF can not map them.

But... there is a way that may help you out. You could create two derived classes from ArCode and let Invoice refer to those by single-property associations. But then you have to divert from the model as such and fool EF a bit by defining a single key:

public abstract class ArCode { ... } // abstract!

public class TermsCode : ArCode { }

public class ShipViaCode : ArCode { }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Invoice>().ToTable("IHSHDR");

    modelBuilder.Entity<Invoice>().HasOptional(i => i.Terms).WithOptionalDependent().Map(m => m.MapKey("terms_cod"));
    modelBuilder.Entity<Invoice>().HasOptional(i => i.ShipVia).WithOptionalDependent().Map(m => m.MapKey("shp_via_cod"));

    modelBuilder.Entity<ArCode>().HasKey(a => a.Code).ToTable("ARCODS");
    modelBuilder.Entity<TermsCode>().Map(m => m.Requires("CodeType")
        .HasValue("T").HasColumnType("varchar").HasMaxLength(1).IsRequired())
        .ToTable("ARCODS");
    modelBuilder.Entity<ShipViaCode>().Map(m => m.Requires("CodeType")
        .HasValue("S").HasColumnType("varchar").HasMaxLength(1).IsRequired())
        .ToTable("ARCODS");

    base.OnModelCreating(modelBuilder);
}

public class Invoice
{
    [Column("pi_hist_hdr_invc_no"), Key]
    public int InvoiceNumber { get; set; }

    public ShipViaCode ShipVia { get; set; }

    public TermsCode Terms { get; set; }
}

This may work for you if you don't have to insert ARCODS records through EF. It won't allow you to insert records with identical Codes, although the database would allow it. But I expect the content of ARCODS to be pretty stable and maybe it is enough to fill it with a script.

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