Phi*_*ler 12 c# entity-framework navigation-properties ef-code-first entity-framework-5
使用EF 5,Code First.
我想对我的实体进行建模,使得导航属性仅存在于关系的一侧.
所以如果我有一个表格Widget和一个表格WidgetType:
public class Widget
{
public int Id { get; set; }
public int WidgetTypeId { get; set; }
public WidgetType WidgetType { get; set; }
}
public class WidgetType
{
public int Id { get; set; }
//note there is no collection of Widgets here
}
public class WidgetMap : EntityTypeConfiguration<Widget>
{
public WidgetMap()
{
HasKey(t => t.Id);
//totable, etc.
HasRequired(t => t.WidgetType); //what else is needed?
}
}
Run Code Online (Sandbox Code Playgroud)
我永远不会想要从widgetType的角度来获取小部件,所以对我来说无论如何都没有WidgetType实体上的导航属性.
如何在不必向WidgetType添加属性的情况下完成代码示例中提到的映射代码?这可能吗?
mas*_*wok 15
我知道有一个公认的答案,但上面的解决方案对我不起作用,我不得不调整一些.
我正在使用Entity Framework 6并遇到类似的问题.我有一个名为BaseEntity的表,它有一个指向UserAccount表的CreatedByID字段.
这在我的UserAccount类中创建了一个类型为BaseEntity的ICollection.我能够通过在BaseEntity映射中使用以下代码来解决这个问题:
this.HasOptional(t => t.UserAccount)
.WithMany()
.HasForeignKey(t => t.CreatedByID);
Run Code Online (Sandbox Code Playgroud)
然后,我能够从UserAccount类中删除BaseEntity集合,该类在EF6中创建了单向一对多映射.
UserAccount条目是可选的,因为UserAccount继承自BaseEntity.如果这是模型中的必需属性,请确保使用HasRequired().
mat*_*mmo 10
根据评论的要求,这是我的答案.
你应该试试:
HasRequired(t => t.WidgetType).WithRequired().HasForeignKey(t => t.FKField);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4850 次 |
| 最近记录: |