依赖于现有属性的导航属性

时间:2017-09-18 11:08:28

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

我有一个类Log,其属性为Entity。此实体将引用共享基类的应用程序中的其他对象(CustomerSupplierInvoiceCredit)。

public class Log
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public LogCode Code { get; set; }    
    public string Message { get; set; }
    public string StackTrace { get; set; }
    public string SourceID { get; set; }
    public DateTime DateCreated { get; internal set; }
    public bool Acknowledged { get; set; }
    public EntityType EntityType { get; set; }    
    public BaseModel Entity { get; set; }
}

EntityType属性包含enum,我可以用它来确定实体的类型。

public enum EntityType
{
    Customer,
    Supplier,
    Invoice,
    Credit,
}

数据库中的表存储了该实体的ID,但由于每个实体类型都存储在不同的表中,因此我很难收集此实体。

我已尝试修改EntityType的设置者以收集正确的实体,但Log没有引用DbContext

没有EF我会打开实体类型并使用不同的服务对象加载正确的实体,但有没有办法让我可以设置实体框架来使用EntityType来收集正确的Entity

1 个答案:

答案 0 :(得分:0)

我认为你应该实现 Table per Concrete Type (TPC)方法。唯一的限制是:您必须使用Guid类型的Id代替int,或者离开int,但在这种情况下,您应该手动为其分配值。< / p>

public abstract class BaseModel 
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id {get;set;}
    public string SomeCommonProperty {get;set;}
}    

public class Log
{
    //other properties...
    //EntityType is not needed, but you can leave it    
    public EntityType EntityType { get; set; }
    public virtual BaseModel Entity { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<BaseModel> Entities  { get; set; }
    public DbSet<Log> Logs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Customers");
        });     
        modelBuilder.Entity<Supplier>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Suppliers");
        });            
    }
}

<强>用法

var suppliers = ctx.Entities.OfType<Supplier>()
      .Where(x => x.SupplierProperty == "1").ToList();

var supplier = (log.Entity as Supplier);
var customer = (log2.Entity as Customer);