实体框架代码首先映射连接表中的复合键,其中外键未在模型中公开
我有一个连接表,其中有一个与连接相关的附加字段:
VirtualDatastreamId INT NOT NULL
DatastreamId INT NOT NULL
FormulaElement INT NOT NULL
所有列都是主键。
它映射到的 POCO 是:
public class VirtualDatastreamMap
{
public virtual Datastream Datastream { get; set; }
public virtual VirtualDatastream VirtualDatastream { get; set; }
public virtual string FormulaElement { get; set; }
}
我在模型中没有外键属性,因为对我来说,外键的概念是一个实现细节,应该由类指定的关系封装。如果可能的话我不想添加这些。
我如何使用 Fluent API 映射它?我希望得到类似下面的内容(不幸的是这不起作用):
modelBuilder.Entity<VirtualDatastreamMap>()
.HasKey(vdm =>
new
{
DatastreamId = vdm.Datastream.Id,
VirtualDatastreamId = vdm.VirtualDatastream.Id,
FormulaElement = vdm.FormulaElement
});
匿名类型的字段名称必须命名为对象不能有两个同名的字段。
我从这个中看到问题这个问题在答案中提出,但似乎没有进一步的内容。
如果不可能,哪个是更好的选择?
- 将外键属性添加到模型中
- 将
Id
字段添加到数据库和模型中
谢谢
I have a join table with an additional field relevant to the join:
VirtualDatastreamId INT NOT NULL
DatastreamId INT NOT NULL
FormulaElement INT NOT NULL
All columns are the primary key.
The POCO this is mapped to is:
public class VirtualDatastreamMap
{
public virtual Datastream Datastream { get; set; }
public virtual VirtualDatastream VirtualDatastream { get; set; }
public virtual string FormulaElement { get; set; }
}
I do not have foreign key properties in the model as, to me, the concept of a foreign key is an implementation detail and should be encapsulated by the relationships specified by the class. I'd prefer not to add these if possible.
How do I map this with Fluent API? I was hoping for something like the below (which unfortunately doesn't work):
modelBuilder.Entity<VirtualDatastreamMap>()
.HasKey(vdm =>
new
{
DatastreamId = vdm.Datastream.Id,
VirtualDatastreamId = vdm.VirtualDatastream.Id,
FormulaElement = vdm.FormulaElement
});
The field names of the anonymous type have to be named as an object cannot have two fields with the same name.
I see from this question that this issue was raised in the answer but there doesn't seem to be anything further.
If it's not possible, which is a better option?
- Add the foreign key properties to the model
- Add an
Id
field to the database and the model
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
复合主键的每一列都必须映射到实体中的标量属性。您理想的解决方案将行不通。
在选项 2 中,您还必须创建一个唯一密钥并检查唯一密钥违规情况。 EF 没有内置对唯一键的支持。因此我会选择选项1。
Each column of the composite primary key has to be mapped to a scalar property in the entity. Your ideal solution will not work.
In Option 2 you would have to create a unique key also and check for unique key violations. EF does not have built in support for unique keys. Hence I would pick option 1.