Entity Framework: field of composite key cannot be nullable?

asp.net-mvc-3 c# ef-code-first entity-framework

Question

I have a model where the row is the composite 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 causes an error to be thrown.DbEntityValidationException and messageThe 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 commonDbContext descent from with Items classified asDbSet<Item> How come theDate necessary if it can benull (Reported asDateTime? ) ? And how can I permitnull a legitimate value forDate ?

1
17
6/4/2012 8:43:34 PM

Accepted Answer

Raphael's response directed me to a different search. Cobsy's response as to why it is not feasible is as follows:

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

In essence:NULL == NULL -> false

Wierd. For me, adding an Id column to the Model is the answer.

By the way, MySQL allows me to have a schema without declaring the Primary Key, but EF complains about this:-(.

11
5/23/2017 12:25:49 PM

Popular Answer

For any portion of a primary key, neither Oracle nor Sql Server allow it.

On this data, though, you may impose a unique restriction.

Consequently, you can only do so once.

UserId = 2, Date = null

Then

UserId = 2, Date = <NOT NULL>

Code First does not directly support the creation of unique constraints, but consider SMO.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow