实体框架1:1关系标识列

时间:2012-06-08 20:21:41

标签: c# entity-framework

我无法通过关系和两个标识列来保存两个单独的表。我不断收到错误,如ReferentialConstraint中的依赖属性映射到存储生成的列。专栏:'OlsTerminalId'。我无法想象这种设置是不正常的。

[DataContract]
    public class OlsData {
        private static readonly DateTime theUnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OlsDataId { get; set; }

    [DataMember(Name = "id")]
    public int Id { get; set; }

    public DateTime Timestamp { get; set; }

    [DataMember(Name = "created")]
    [NotMapped]
    public double Created {
        get { return (Timestamp - theUnixEpoch).TotalMilliseconds; }
        set { Timestamp = theUnixEpoch.AddMilliseconds(value); }
    }

    [InverseProperty("OlsData")]
    [DataMember(Name = "terminal")]
    public virtual OlsTerminal OlsTerminal { get; set; }
}

[DataContract]
public class OlsTerminal {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OlsTerminalId { get; set; }

    public int OlsDataId { get; set; }

    [DataMember(Name = "account")]
    [NotMapped]
    public virtual OlsAccount OlsAccount { get; set; }

    [DataMember(Name = "terminalId")]
    public string TerminalId { get; set; }

    [DataMember(Name = "merchantId")]
    public string MerchantId { get; set; }

    public virtual OlsData OlsData { get; set; }
}

 public class OlsDataContext : DbContext {
        protected override void OnModelCreating(DbModelBuilder aModelBuilder) {
            aModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public OlsDataContext(string aConnectionString) : base(aConnectionString) {}
        public DbSet<OlsData> OlsData { get; set; }
        public DbSet<OlsTerminal> OlsTerminal { get; set; }
        public DbSet<OlsAccount> OlsAccount { get; set; }

    }

1 个答案:

答案 0 :(得分:0)

这是因为EF中的1:1关系总是建立在主键上。因此,OlsTerminal表中的FK必须由OlsTerminalId和FK无法自动生成 - 它必须是来自OlsData的PK值。

必须以这种方式完成的原因是要求依赖实体中FK值的唯一性构建真实的1:1而不是1:N。 EF不支持唯一约束/候选键,因此如何强制执行唯一性的唯一方法是在依赖实体的PK上使用FK。