Linq 2 SQL一对零或一对关系可能吗? [英] Linq 2 SQL One to Zero or One relationship possible?
问题描述
是否可以在Linq2SQL中创建一对零或一个关系?
Is it possible to create a one to zero or one relationship in Linq2SQL?
我的理解是,要创建一对一关系,您需要在每个表的PK上创建FK关系.
My understanding is that to create a one to one relationship you create a FK relationship on the PK of each table.
但是您不能使PK可为空,所以我不知道如何使一对零或一种关系起作用?
But you cannot make the PK nullable, so I don't see how to make a one to zero or one relationship work?
我正在使用设计器自动创建模型-所以我想知道如何设置SQL表以诱导这种关系-而不是一些自定义的ORM代码.
I'm using the designer to automatically create the model - so I would like to know how to set up the SQL tables to induce the relationship - not some custom ORM code.
推荐答案
您是部分正确的人,但是您的想法有些混乱.
You're partially correct...but your mixing things a little.
您不能使主键字段为空.那部分是正确的.但是,对象上具有一->零或一关系的外键字段可以为空.
You cannot make a primary key field null. That part is correct. But the foreign key field on the object holding the one -> zero or one relationship CAN be null.
在LINQ to SQL中,一个->零或一个关系将只是引用另一个LINQ to SQL类但允许为空的字段.
In LINQ to SQL, the one -> zero or one relationship will just be a field that references another LINQ to SQL class but allows nulls.
示例表
create table Child (
id int identity(1,1),
name varchar(max),
primary key (id))
create table Parent (
id int identity(1,1),
childId int,
name varchar(max),
primary key (id),
foreign key (childId) references Child(id))
使用这些表,您应该从父级到子级得到一个-> 0或一个,从子级到父级得到一个->许多(一个孩子可以有很多父母).
Using those tables, you should get a one -> zero or one from Parent to Child and a one -> many from Child back to Parent (one child can have many parents).
这篇关于Linq 2 SQL一对零或一对关系可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!