Code First CTP4: Table with no primary key?

守給你的承諾、 提交于 2019-12-10 18:36:03

问题


With Entity Framework and Code First, is it possible to let it create and use a table with no primary keys? I can't get this setup to work:

public class Report
{
    public virtual int ReportId
    public virtual ICollection<ReportChanges> ReportChanges
}

public class ReportChanges
{
    public virtual Report Report
    public virtual string EditorName
    public virtual DateTime Changed
}

Note that I've excluded assigning a primary key in ReportChanges. But with this setup I get: "Unable to infer a key for entity type 'ReportChanges'".

Either I'm missing something, or Code First doesn't support tables with no primary keys. What is correct? Thanks.


回答1:


The EF can support a table with no PI if there is still a way to uniquely identify a row, but it can't infer the unique identifier without a proper PK. In other words, lie to the EF and say that there is a PK, say, on Report and Changed.




回答2:


EF needs a way to keep track of its own internal changes. Here's a code sample to help others who've Googled this:

public class YourDataContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ReportChanges>().HasKey(x => new {x.Report, x.Changed});
    }
}

The "new {x.Report, x.Changed}" creates a fake composite key allowing EF to uniquely point to a row internally.



来源:https://stackoverflow.com/questions/4068920/code-first-ctp4-table-with-no-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!