Linq 2 SQL One to Zero or One relationship possible?

浪子不回头ぞ 提交于 2019-12-06 12:41:34

问题


Is it possible to create a one to zero or one relationship in Linq2SQL?

My understanding is that to create a one to one relationship you create a FK relationship on the PK of each table.

But you cannot make the PK nullable, so I don't see how to make a one to zero or one relationship work?

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.


回答1:


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.

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.

Example Tables

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

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).




回答2:


If you're wanting Z cardinality, try something like:

CREATE TABLE parent (id INTEGER NOT NULL PRIMARY KEY);
CREATE TABLE child (id INTEGER NOT NULL PRIMARY KEY REFERENCES parent (id));

You're creating a common primary key between the two tables. You will be unable to insert rows into child if the PK doesn't exist in the parent.

SELECT p.*, c.* FROM parent p LEFT JOIN child c ON c.id=p.id

will return NULL for c.* where no relationship exists.



来源:https://stackoverflow.com/questions/1921788/linq-2-sql-one-to-zero-or-one-relationship-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!