实体与实体列表之间的多个关联

时间:2014-03-07 03:46:44

标签: c# .net entity-framework

在我的数据库中,我想说我有两个表,tblFoo和tblBar

tblFoo有列

ID, Name, SomeFooThing, BarGroup, DeviceID, CountryCode, UserID

tblBar有列

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; }
}

我如何建立Foo和Bar之间的关联?

如果我在SQL中这样做,我会做(给你更多的想法)

SELECT tblBar.ID, tblBar.Name, tblBar.SomeBarThing, tblBar.BarGroup, 
tblBar.DeviceID, tblBar.CountryCode, tblBar.UserID, Foo.ID as FooID 
FROM tblBar INNER JOIN tblFoo ON tblBar.BarGroup=tblFoo.BarGroup AND 
tblBar.DeviceID=tblFoo.DeviceID AND tblBar.CountryCode=tblFoo.CountryCode 
AND tblBar.UserID=tblFoo.UserID

我正在使用实体框架6

1 个答案:

答案 0 :(得分:1)

您只需在Foo类:

中添加Bar导航属性即可
[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

相关问题