简体   繁体   English

一对一的EF关系

[英]One to one EF relationship

I have a database that looks like this:我有一个看起来像这样的数据库:

在此处输入图片说明

Where TableA is the principal and TableB is the dependent.其中 TableA 是主体,TableB 是从属。

I'm trying to create this relationship in the DB using Entity Framework.我正在尝试使用实体框架在数据库中创建这种关系。 The connection from TableB to TableA works, but the opposite does not (TableA to TableB).从 TableB 到 TableA 的连接有效,但相反(TableA 到 TableB)不起作用。

public partial class TableA
{
    [Key]
    public long id { get; set; }
    public virtual TableB tableB { get; set; }
}

public partial class TableB
{
    [Key]
    public long id { get; set; }
    public long TableA_ID { get; set; }
    public string value { get; set; }   
    [ForeignKey("TableA_ID")]   
    public virtual TableA tableA { get; set; }
}

Each time I get the error:每次我收到错误:

Because the dependent role properties are not the key properties, the upper bound of the multiplicity of the dependent role must be '*'因为依赖角色属性不是关键属性,所以依赖角色的重数上限必须是'*'

or the error:或错误:

The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations必须使用关系流畅 API 或数据注释显式配置此关联的主体端

I tried adding [Required] in TableB above public virtual TableA tableA and in other places but nothing seems to work.我尝试在public virtual TableA tableA上方的 TableB 和其他地方添加[Required]但似乎没有任何效果。

Can you please help me create such relationship (using data annotations only, if possible)?你能帮我创建这样的关系吗(如果可能,只使用数据注释)?

DataSet ds = new DataSet(); 
ds.Tables.Add(TableA);
ds.Relations.Add("TableB", TableA.Columns["id"], TableB.Columns["TableA_ID"]);
ds.Relations["TableB"].Nested = true;

If I understand correctly.如果我理解正确的话。 You can try this.你可以试试这个。

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

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