我在数据库中有2个表:ReceivedGoods
和ReceivedGoodsProperties
ReceivedGoods
包含ReceivingId
作为PK,并且必须在ReceivedGoodsProperties
中具有其扩展数据,其中ReceivingId
包含ReceivedGoods
的{{1}}作为FK。但是,当前的ReceivingId
具有自己的PK ReceivedGoodsProperties
,因此与FK不同。所以我有以下内容:
Id
我想获取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; }
}
对象并具有自动加载的属性,但是我不知道如何在EF中进行设置。
我已经尝试过类似的操作(从ReceivedGoods
侧面映射):
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.
中注释掉ReceivingId
时,不会引发较高的异常,除了ReceivedGoodsProperties
属性以外,ReceivedGoods
已正确加载。
有人可以解释我,在这种情况下如何进行一对一映射吗?
答案 0 :(得分:0)
您可以尝试:
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
答案 1 :(得分:0)
尝试通过这种方式定义关系:
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);