Entity Framework: field of composite key cannot be nullable?

前端 未结 3 1411
广开言路
广开言路 2020-12-03 17:22

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         


        
相关标签:
3条回答
  • 2020-12-03 17:37

    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.

    0 讨论(0)
  • 2020-12-03 17:47

    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 :-(.

    0 讨论(0)
  • 2020-12-03 17:47

    It is not possible. Every RDBMS requirement is, that primary key must be not nullable.

    0 讨论(0)
提交回复
热议问题