如何使用LINQ和导航属性连接表

时间:2016-10-21 07:14:40

标签: c# linq entity-relationship navigation-properties

Previous question link

考虑我之前的问题(我给它添加了一个链接)我需要获得一些不同的信息。

这是一个DB结构我只添加了导航属性

?

到传输类

public virtual ICollection<Accident> Accidents { get; set; } 

如果我想发生所有意外,我会使用

public class Person
{
    [Key]
    public int PersonID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transport
{
    [Key]
    public int TransportID { get; set; }
    public string Model { get; set; }
    public string Brand { get; set; }
    public virtual ICollection<Accident> Accidents { get; set; }
}

public class Accident
{
    [Key]
    public int AccsidentID { get; set; }
    public DateTime AccidentDate { get; set; }
    public int TransportID { get; set; }
    [ForeignKey("TransportID")]
    public virtual Transport Transport { get; set; }

    public int PersonID { get; set; }
    [ForeignKey("PersonID")]
    public virtual Person Person { get; set; }
}
public class AccsidentObject
{
    [Key]
    public int AccidentID { get; set; }
    public DateTime AccidentDate { get; set; }
    public int TransportID { get; set; }
    public string Model { get; set; }
    public string Brand { get; set; }
    public int PersonID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
 }

如果我想选择添加了特定事故数据的TransportObject

,那将是什么代码
var accidents = DBContext.Accidents.Select( a => new AccidentObject 
{ 
    AccidentID = a.AccidentId,
    AccidentDate 
    TransportID 
    Model 
    Brand = a.Transport.Brand,
    PersonID = a.Person.PersonID,
    FirstName 
    LastName 
});

1 个答案:

答案 0 :(得分:1)

使用此代码

var transports = DBContext.Transports
        .SelectMany(
            x => x.Accidents, 
            (t, a) => new TransportObject 
            {
                TransportID = t.TransportID,
                Model = t.Model,
                Brand = t.Brand,
                AccidentID = a.AccidentId,
                AccidentDate = a.AccidentDate
            }
        );

有关MSDN中选择多个的更多信息。