对多个字段的外键约束 [英] Foreign key constraint to multiple fields

查看:390
本文介绍了对多个字段的外键约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 });

推荐答案

我通常在SQL实用程序(例如SQL Server Management Studio)中为SQL构建表/关系。 br />


除此之外,我仍然会遵循相同的路径:创建表,设置主键和关系作为谨慎的SQL查询,而不是参数化C#代码。



我更喜欢让SQL处理SQL(即使通过C#,C ++,php,......)

建立SQL连接

设置查询字符串

执行它们
I usually build tables/relationships for SQL in a SQL utility (such as SQL Server Management Studio).

That aside, I would still following something of the same route: create the tables, set primary key(s), and the relationships as discreet SQL Queries and not parametized with C# code.

I prefer letting SQL handle SQL (even if via C#, C++, php, ...)
Establish a SQL connection
Set the Query Strings
Execute them


这篇关于对多个字段的外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆