Linq 2 SQL One to Zero or One relationship possible?

流过昼夜 提交于 2019-12-04 18:19:06

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

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.

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