Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体和实体列表之间的多个关联_C#_.net_Entity Framework - Fatal编程技术网

C# 实体和实体列表之间的多个关联

C# 实体和实体列表之间的多个关联,c#,.net,entity-framework,C#,.net,Entity Framework,在我的数据库中,假设我有两个表,tblFoo和tblBar tblFoo具有列 ID, Name, SomeFooThing, BarGroup, DeviceID, CountryCode, UserID ID, Name, SomeBarThing, BarGroup, DeviceID, CountryCode, UserID tblBar具有列 ID, Name, SomeFooThing, BarGroup, DeviceID, CountryCode, UserID ID, N

在我的数据库中,假设我有两个表,tblFoo和tblBar

tblFoo具有列

ID, Name, SomeFooThing, BarGroup, DeviceID, CountryCode, UserID
ID, Name, SomeBarThing, BarGroup, DeviceID, CountryCode, UserID
tblBar具有列

ID, Name, SomeFooThing, BarGroup, DeviceID, CountryCode, UserID
ID, Name, SomeBarThing, BarGroup, DeviceID, CountryCode, UserID
我有两个实体类:

[Table("tblFoo")]
public class Foo
{
    [Key]
    public int? ID { get; set; }
    public string Name { get; set; }
    public string SomeFooThing { get; set; }
    public int BarGroup { get; set; }
    [Key]
    public int DeviceID { get; set; }
    [Key]
    public int CountryCode { get; set; }
    [Key]
    public int UserID { get; set; }

    public virtual IEnumerable<Bar> Bars { get; set; }
}

[Table("tblFoo")]
public class Bar
{
    [Key]
    public int? ID { get; set; }
    public string Name { get; set; }
    public string SomeBarThing { get; set; }
    public int BarGroup { get; set; }
    [Key]
    public int DeviceID { get; set; }
    [Key]
    public int CountryCode { get; set; }
    [Key]
    public int UserID { get; set; }
}

我使用的是实体框架6

您只需在
Bar
类中添加
Foo
导航属性即可:

[Table("tblBar")]
public class Bar
{
    // (...)

    public virtual Foo Foo { get; set; }
}
然后,您可以执行以下查询:

var query = from b in ctx.Bars
            let f = b.Foo
            select { ... }

EF将为您添加必要的
JOIN

您需要为两个型号添加外键分配。退房顺便说一句,您的SQL语句没有显示两个表之间的任何关系。已更改该语句。如何添加多个外键?是的,但它会考虑DeviceID、CountryCode、BarGroup和UserID吗?是的,会。或者更好:应该是这样。这仅仅是因为列的命名吗?只是试着去理解。如果列具有不同的名称,但我希望它们在联接中相等,该怎么办?外键也必须包含所链接表中的所有主键列。这就是它的工作原理。但我可能没有正确理解你的问题。你不想同时成为FK吗?如果是这样,您必须使用
[ForeignKey]
属性将它们标记为FK。
ID
DeviceID
CountryCode
UserID
都是这两个表上的主键。那么这是否意味着我应该在它们上面有
Key
ForeignKey