Can we have table without primary key in entity framework?

后端 未结 6 1926
北恋
北恋 2020-11-30 12:02

I was just practicing code first new database entity framework from msdn, I wanna know whether a table without primary key can be created in code first new database EF?

6条回答
  •  -上瘾入骨i
    2020-11-30 12:35

    Sometimes adding PK is not possible because it can be read-only, super protected database of a client which you have to use. EF throws exception even on SELECT operations. When I faced that issue I was able to solve it like this (names are artificial):

    [Table( "WeirdTable", Schema = "SomeSchema" )]
    public class WeirdTable
    {
        [Column( "ID1" )]
        public int Id1 { get; set; }
    
        [Column( "ID2" )]
        public int Id2 { get; set; }
    }
    

    In the code file of context:

    protected override void OnModelCreating( DbModelBuilder model_builder )
    {
        base.OnModelCreating( model_builder );
        model_builder.Entity().HasKey(
            t => new { t.Id1, t.Id2 }
        );
    }
    

    So basically you just need to specify which columns can be primary key.

提交回复
热议问题