简体   繁体   English

关联实体在LINQPad中有效,但在运行时为null

[英]Association entity is valid in LINQPad but null at runtime

Let's assume I have some car related entities. 假设我有一些与汽车相关的实体。 A Vehicle class and a VehicleType class. Vehicle类和VehicleType类。

public class Vehicle
{
    public int Id {get; set;}
    public string Name {get; set}
    public int VehicleTypeId {get; set;}
    public virtual VehicleType VehicleType {get; set;}
}

public class VehicleType
{
    public int Id {get; set;}
    public string VehicleTypeName {get; set}
    public ICollection<Vehicle> Vehicles {get; set;}
    public ICollection<Price> Prices {get; set;}
}

public class Price
{
    public int Id {get; set;}
    public int Price {get; set;}
    public int VehicleTypeId {get; set;}
    public virtual VehicleType VehicleType {get; set;}
}

The VehicleType table serves as a relationship table to both the Vehicle table and the Price table. VehicleType表用作Vehicle表和Price表的关系表。 I am trying to use LINQ to get at the Price for a given Vehicle based upon it's VehicleType ... 我正在尝试使用LINQ根据其VehicleType获取给定VehiclePrice ...

var myVehicle = dbContext.Vehicles.FirstOrDefault(v => v.Id == 1234);
var myVehiclePrice = myVehicle.VehicleType.Prices.Select(p => p.Price);

Now when using LINQPad this query works well when I use my database as the source. 现在,当使用LINQPad时,当我将数据库用作源时,此查询效果很好。 I get back the Price as expected. 我得到了预期的价格。 However, when using this inside Visual Studio an exception is thrown on .. 但是,在Visual Studio中使用此方法时,将引发异常。

var myVehiclePrice = myVehicle.VehicleType.Prices.Select(p => p.Price);

The exception is that VehicleType is null. 唯一的例外是VehicleType为null。 I know there is data there, I am just not sure why VehicleType is showing as null . 我知道那里有数据,我只是不确定为什么VehicleType显示为null

And yes I am using the same connection string in my web.config and LINQPad. 是的,我在web.config和LINQPad中使用了相同的连接字符串。

EDIT: I should note that when using LINQPad I was using C# Expressions rather than C# Statements. 编辑:我应该注意,当使用LINQPad时,我使用的是C#表达式而不是C#语句。

Solution : I was able to get it working. 解决方案 :我能够使其正常运行。 In the end, in order to get the prices, I had to include BOTH the VehicleType and Price entities in the Include statement. 最后,为了获得价格,我必须在Include语句中同时包含VehicleTypePrice实体。

var myVehcilePrice = myVehicle.Include("VehicleType.Prices").Single(v => v.Id == 1234).VehicleType.Prices

Note that you want to include the association name in the Include statement. 请注意,您要在Include语句中包括关联名称。 Thanks to TheGeekYouNeed for the help on Include. 感谢TheGeekYouNeed对Include的帮助。

var myVehicle = dbContext.Vehicles.Where(v => v.Id == 1234).Include("VehicleType").FirstOrDefault();

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

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