【发布时间】:2011-10-24 06:35:26
【问题描述】:
[Q:] 是否可以在 EF 中使用 FK 作为鉴别器,人们提出了哪些解决方法?
场景
EF 对象
public class List
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ListItem> Items { get; set; }
}
public abstract class ListItem
{
public int Id { get; set; }
public List List { get; set; }
public string Text { get; set; }
}
数据库
不被 EF 独占使用(即无法更改)的现有 DB 具有如下字段:
List
Id int not null (identity)
Name varchar
ListItem
Id int not null (identity)
ListId int not null (FK to List.Id)
Text varchar
期望的结果
我希望 List 的 Id 成为 ListItem 的鉴别器。即,对于列表中的每个条目,实现了一个从 ListItem 派生的单独类。
例如对于列表 [Id:1]
public class PersonListItem : ListItem
{
public int PersonId { get; set; }
public Person Person { get; set; }
}
public class ListItemConfiguration : EntityTypeConfiguration<ListItem>
{
Map<PersonListItem>(m => m.Requires("ListId").HasValue(1));
}
在上述情况下,保存更改会导致 SQL 异常,因为 EF 在创建新的 ListItem 实例时尝试插入 List_Id。 List_Id 不是一个字段,我不能将 ListId 映射为 ListItem 上的属性,因为它不能用作鉴别器。
到目前为止我的解决方案...
This Q&A 解释了为什么他们决定不允许 FK 作为鉴别器。
到目前为止,我的解决方法是向数据库添加另一个字段以用作鉴别器,然后使用插入触发器将其设置为与 ListId 相同的值(以处理非 EF 插入)和然后将 ListId 导航属性添加到 ListItem 实体。
有人有任何建议/替代方案吗?
【问题讨论】:
标签: sql-server entity-framework-4.1