简体   繁体   English

Code First CTP4:没有主键的表?

[英]Code First CTP4: Table with no primary key?

With Entity Framework and Code First, is it possible to let it create and use a table with no primary keys? 使用Entity Framework和Code First,是否可以让它创建和使用没有主键的表? 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. 请注意,我已排除在ReportChanges中分配主键。 But with this setup I get: " Unable to infer a key for entity type 'ReportChanges '". 但是通过这种设置,我得到:“ 无法推断实体类型'ReportChanges ' 的密钥 ”。

Either I'm missing something, or Code First doesn't support tables with no primary keys. 要么我错过了什么,要么Code First不支持没有主键的表。 What is correct? 什么是正确的? Thanks. 谢谢。

EF needs a way to keep track of its own internal changes. EF需要一种方法来跟踪自己的内部变化。 Here's a code sample to help others who've Googled this: 这是一个代码示例,以帮助其他人使用Google搜索:

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. “new {x.Report,x.Changed}”创建一个伪复合键,允许EF在内部唯一地指向一行。

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. 如果仍然有一种唯一标识行的方法,EF可以支持没有PI的表, 如果没有适当的PK,它就无法推断出唯一标识符。 In other words, lie to the EF and say that there is a PK, say, on Report and Changed . 换句话说,欺骗EF,并说在ReportChanged上有一个PK。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM