views:

466

answers:

2

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.

A: 

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

Justin Niessner
"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."How do I model that in the database? If I create a column that allows nulls and then use that as the FK, I get a one to many relationship - even if I put a unique constraint on that column.
Mr. Flibble
A: 

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.

Jim H.