问题描述
Mates,
我有一个SQL Server表< entity>这是在一定的管理。表< entity>与< entitystatus>有关系。
< entity>
Id(int,PK,auto-increment)
AdminstrationId int
状态int
名称varchar
....
< entitystatus>
Id(int,PK,auto-increment)
AdminstrationId int
Number int
名称varchar
正如您所看到的,两个表都有一个Id字段,它是PK并且自动递增。
现在我希望实体框架在两个AdministrationId字段和< entity> .Status&之间创建关系。 < entitystatus>数字字段。
我该怎么做?
下面的代码你试过什么,实际上适用于关系,但它将Id字段作为状态表的PK删除。当我在< entitystatus>中输入新的状态值时,这会导致错误。桌子
我尝试过:
Mates,
I have a SQL Server table <entity> which is in a certain administration. The table <entity> has a relation with <entitystatus>.
<entity>
Id (int, PK, auto-increment)
AdminstrationId int
Status int
Name varchar
....
<entitystatus>
Id (int, PK, auto-increment)
AdminstrationId int
Number int
Name varchar
As you can see, both tables have a Id field which is a PK and have auto-increment on.
Now I want entity framework to create a relation between both AdministrationId fields, and the <entity>.Status & <entitystatus>Number field.
How can I do this?
The code below in the 'what have you tried', actually works for the relation, but it removes the Id field as a PK of the status table. This causes an error when I enter new status values in the <entitystatus> table
What I have tried:
modelBuilder.Entity<Entity>()
.HasKey(c => new { c.AdministrationId, c.Number });
modelBuilder.Entity<Entity>()
.HasRequired(p => p.EntityStatus)
.WithMany(x => x.Entities)
.HasForeignKey(p => new { p.AdministrationId, p.Status });
推荐答案
这篇关于对多个字段的外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!