我的数据库里有两个表:ReceivedGoods和ReceivedGoodsProperties ReceivedGoods包含ReceivingId作为PK,它的扩展数据必须在ReceivedGoodsProperties中包含ReceivingId作为FK引用ReceivedGoods的ReceivingId。但是当前的ReceivedGoodsProperties有它自己的PK Id,因此不同于FK。所以我有以下内容:
public class ReceivedGoods
{
...
public int ReceivingId { get; set; }
...
public virtual ReceivedGoodsProperties properties { get; set; }
}
public class ReceivedGoodsProperties
{
...
public int Id { get; set; } // This is PK
public int ReceivingId { get; set; } // This is FK
...
public virtual ReceivedGoods goods { get; set; }
}我想得到ReceivedGoods对象和属性自动加载,但我不能弄清楚,如何在EF内设置这一点。我尝试过这样的方法(从ReceivedGoodsProperties侧映射):
this.HasRequired(p => p.goods)
.WithRequiredDependent(d => d.properties)
.Map(m => m.MapKey("ReceivingId"));但我最终得到了以下错误:
ReceivingId: Name: Each property name in a type must be unique. Property
name 'ReceivingId' is already defined.在ReceivedGoodsProperties中注释掉ReceivingId时,不会引发上部异常,ReceivedGoods将正确加载( properties属性除外)。
有人能给我解释一下,在这种情况下如何进行一对一映射吗?
发布于 2018-07-19 00:36:52
你能不能试试:
public class ReceivedGoods
{
...
public int ReceivingId { get; set; }
...
public virtual ReceivedGoodsProperties properties { get; set; }
}
public class ReceivedGoodsProperties
{
...
public int Id { get; set; } // This is PK
[ForeignKey( "goods " )]
public int ReceivingId { get; set; } // This is FK
...
[Required]
public virtual ReceivedGoods goods { get; set; }
}顺便说一句,在C#中,标准指南是给PascalCase成员的,所以Goods和Properties
发布于 2018-07-19 00:37:16
尝试这样定义关系:
this.HasRequired(p => p.goods)
.WithRequiredDependent(p => p.properties)
.HasForeignKey(p => p.ReceivingId);如果您遵循标准的EF命名约定,它通常可以自己弄清楚这些关系。只有当您的导航属性名称与类名称不对应时,或者在源表中有多个指向同一目标的FK时,您才会真正遇到麻烦。
如果希望导航属性“自动”填充,请在查询上使用Include扩展方法,如:context.Goods.Include(g=>g.properties)。除非您想使用延迟加载,否则不必将它们声明为virtual。
您可能需要从另一个实体获得此结果:
this.HasRequired(p => p.properties)
.WithRequiredPrincipal(p => p.goods)
.HasForeignKey(p => p.ReceivingId);https://stackoverflow.com/questions/51406698
复制相似问题