C# EF:首先是一对多映射代码
我有几个实体。每个实体都包含许多在继承的BaseEntity中定义的可选文档C# EF:首先是一对多映射代码,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,我有几个实体。每个实体都包含许多在继承的BaseEntity中定义的可选文档 public class Address : BaseEntity { public virtual Address Parent { get; set; } public string Name1 { get; set; } public string Name2 { get; set; } public string Additional { get; set; } p
public class Address : BaseEntity
{
public virtual Address Parent { get; set; }
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Additional { get; set; }
public string Street { get; set; }
public string HousNr { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public virtual Document Image { get; set; }
public virtual ICollection<AddressContact> AddressContacts { get; set; }
public virtual ICollection<Address> AddressPersons { get; set; }
}
public abstract class BaseEntity
{
public Guid Id { get; set; }
public bool IsDeleted { get; set; }
public bool IsSystem { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Document> Documents { get; set; }
public DateTime CreatedTime { get; set; }
public string CreatedUser { get; set; }
public DateTime? LastModifiedTime { get; set; }
public string LastModifiedUser { get; set; }
}
这里是我的基本映射:
public abstract class BaseEntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : BaseEntity
{
public abstract string TableName { get; }
public virtual bool HasDocument { get {return false;} }
public BaseEntityConfiguration()
{
HasKey(x => x.Id);
Property(x => x.CreatedUser).IsRequired().HasMaxLength(100);
if (HasDocument)
{
//TODO: general-Mapping for Documents??
}
else
{
Ignore(x => x.Documents);
}
ToTable(TableName);
}
}
公共抽象类BaseEntityConfiguration:EntityTypeConfiguration其中tenty:BaseEntity
{
公共抽象字符串TableName{get;}
公共虚拟bool HasDocument{get{return false;}}
公共基础实体配置()
{
HasKey(x=>x.Id);
属性(x=>x.CreatedUser).IsRequired().HasMaxLength(100);
如果(文件)
{
//TODO:文档的常规映射??
}
其他的
{
忽略(x=>x.Documents);
}
ToTable(表名);
}
}
我如何定义我的代码优先映射,以便最终所有提交实体都只存在一个通用文档表?我不太确定你在问什么,你能进一步解释吗?你有很多例子,但你的问题还不清楚。我会为每种类型创建一个简单的EntityTypeConfiguration类,简单明了。。此外,若您什么也不做,那个么特殊的实体框架将应用TPH映射,我认为您需要的是TPH映射(一个通用文档表)。这不一定是最好的映射策略!我只需要数据库中的一个文档表。我将有许多实体,如地址与文档实体具有相同的关系。我会在每个提交实体没有fk列的情况下这样做……好的,这是关于多态关联的。有。有了EF,我会选择数据库中有外键的模型:选项3多态关联是关键!非常感谢。
public abstract class BaseEntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : BaseEntity
{
public abstract string TableName { get; }
public virtual bool HasDocument { get {return false;} }
public BaseEntityConfiguration()
{
HasKey(x => x.Id);
Property(x => x.CreatedUser).IsRequired().HasMaxLength(100);
if (HasDocument)
{
//TODO: general-Mapping for Documents??
}
else
{
Ignore(x => x.Documents);
}
ToTable(TableName);
}
}