1

我无法使用关系和两个标识列来保存两个单独的表。我不断收到错误,例如 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; }

    }
4

1 回答 1

0

这是因为 EF 中的 1:1 关系始终建立在主键之上。所以OlsTerminal表中的 FK 必须 byOlsTerminalId并且 FK 不能自动生成 - 它必须是 PK from 的值OlsData

之所以必须这样做,是因为需要依赖实体中 FK 值的唯一性来构建真正的 1:1 而不是 1:N。EF 尚不支持唯一约束/候选键,因此如何强制唯一性的唯一方法是将 FK 放在依赖实体的 PK 上。

于 2012-06-09T09:38:40.993 回答