Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: field of composite key cannot be nullable?

Tags:

I have a model with composite key - the row is the key:

public class Item
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    [Key, Column(Order = 1)]
    public DateTime? Date { get; set; }
}

Running the code below it throws an exception DbEntityValidationException with message: The Date field is required.:

var it = new Item { Date = null, UserId = 2 };
m_Entities.Items.Add(it);
m_Entities.SaveChanges(); // throws exception

(m_Entities is usual DbContext descendant with Items defined as DbSet<Item>) Why is the Date required if it can be null (declared as DateTime?) ? And how to allow null to be a valid value for Date?

like image 716
Zoka Avatar asked Jun 04 '12 20:06

Zoka


People also ask

Can a composite key have nulls?

A composite key cannot be null.

Can a column in composite primary key be NULL?

Hi, In composite primary key columns you cannot pass null values. Each column defined as a primary key would be validated so that null values are not passed on to them. If you have given a Unique constraint then we have a chance of NULL values being accepted.

Can a primary key even be NULL?

Primary key will not accept NULL values whereas Unique key can accept NULL values. A table can have only one primary key whereas there can be multiple unique key on a table. A Clustered index automatically created when a primary key is defined whereas Unique key generates the non-clustered index.

Can primary key have NULL values in Oracle?

PRIMARY KEY Integrity Constraints The Oracle implementation of the PRIMARY KEY integrity constraint guarantees that both of the following are true: No two rows of a table have duplicate values in the specified column or set of columns. The primary key columns do not allow nulls.


2 Answers

Answer from Raphael lead me to another search. Here is the why it is not possible (answer from Cobsy):

What's wrong with nullable columns in composite primary keys?

In short: NULL == NULL -> false

Wierd. The solution for me is to add Id column into Model.

BTW: MySQL allow me not to define Primary Key, then I'm allowed to have such schema - EF complains about not defining the key :-(.

like image 183
Zoka Avatar answered Sep 17 '22 13:09

Zoka


It's not possible with Sql Server, or Oracle for any part of a primary key.

But you can have a unique constraint on these datas.

Which means you can have one time

UserId = 2, Date = null

Then

UserId = 2, Date = <NOT NULL>

You can't create directly unique constraints with Code First, but look at SMO.

like image 23
Raphaël Althaus Avatar answered Sep 20 '22 13:09

Raphaël Althaus