我正在尝试将EF合并到我的应用程序中。我使用EF6和Code First。我的对象模型有一些泛型类,似乎Code First部分接受它(正确生成表和列)。
以下示例:
public class Group : TimeableObject<GroupTimeline> {}
public class GroupTimeline : TimelineBase
{
public GroupTimeline() { }
public string Name {get; set;}
}
public abstract class TimelineBase
{
public int Id { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
}
public abstract class TimeableObject<T>
where T : TimelineBase
{
private DateTime? _snapshotDate;
public TimeableObject()
{
Timelines = new List<T>();
}
public int Id { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public List<T> Timelines { get; set; }
public DateTime SnapshotDate
{
get { //some logic.. }
set { _snapshotDate = value; }
}
public T Timeline
{
get { //some logic.. }
}
}
通过流畅的API我将继承配置为TPC。所以我希望表Group和表GroupTimeline具有GroupTimeline中Group的外键。
首先,除了标识之外,生成的数据库看起来正确。关于这一点的奇怪之处在于EF在例如Id中看到Id属性。在数据库中分组并生成PK。虽然没有身份。对于TimelineBase类中的Id属性也是如此。 其次,我不希望映射属性SnapshotDate。通过流畅的API,我无法达到这个目标。在这里,我得到一个异常,告诉我完整的类被忽略或是通用的。所以我假设EF不支持泛型类,尽管数据库是正确生成的(不是标识)。这背后的故事是什么? 通过使用数据注释,我修复了我的问题。我可以获得属性的标识(在Id属性上):
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
我可以阻止将SnapshotDate属性映射到:
[NotMapped]
低于我的流利配置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Group>().Map(m =>
{
m.MapInheritedProperties();
});
modelBuilder.Entity<GroupTimeline>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Group_Timeline");
});
modelBuilder.Entity<TimeableObject<TimelineBase>>().HasKey(m => m.Id).Property( p => p.Id ).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<TimeableObject<TimelineBase>>().Ignore(m => m.SnapshotDate);
modelBuilder.Entity<TimelineBase>().HasKey(m => m.Id).Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
这是一个例外:
The type 'Data.DataObjectModel.TimeableObject`1[Data.DataObjectModel.TimelineBase]'
was not mapped. Check that the type has not been explicitly excluded by using the
Ignore method or NotMappedAttribute data annotation. Verify that the type was
defined as a class, is not primitive or generic, and does not inherit from
EntityObject.
此致 丹尼尔卡亚