【问题标题】:EF & LINQ: Get object from database cellEF & LINQ:从数据库单元中获取对象
【发布时间】:2015-04-28 16:00:26
【问题描述】:

我首先使用实体​​框架代码,我有三个表(例如):

public class Motorbike()
{
    public int Id {get; set;}
    public string Producent {get; set;}
    public Engine Motor {get; set;}
    public Tire Tires {get; set;}
}

public class Engine()
{
    public int Id {get; set;}
    public int Power {get; set;}
    public decimal Price {get;set;}
}

public class Tire()
{
    public int Id {get; set;}
    public int Size {get; set;}
    public decimal Price {get; set;}
}

这只是一个例子,实际上它更复杂。 Entity Frmaework 为我生成表,但表 Motorbike 有列:IdPowerEngine_Id(仅存储数字 - id 引擎,而不是整个对象)和 Tire_Id(仅存储数字 - id轮胎,而不是整个物体)。

我知道如何插入数据 - 只需创建新的 Motorbike 对象,保存到他的字段数据(对于 EngineTire 字段,我不仅保存整个对象 id)并使用我的上下文中的 .Add() 方法。

但是如何获取摩托车 id 为(例如)1 的行的数据?

我尝试过这样的事情:

List<Motorbike> motorbikes= new List<Motorbike>();
var list = _context.Motorbike.Where(p => p.Id == 1);
motorbikes.AddRange(list);

但我总是为 EngineTire 字段设置 null(字段 Id 和 Producent 填写正确)。

【问题讨论】:

  • 你能提供更多关于你的实体框架和数据库定义的信息吗?

标签: c# database linq entity-framework object


【解决方案1】:

使用Include 加载相关实体,例如:

var list = _context.Motorbike
                   .Include(m=> m.Engine)
                   .Include(m=> m.Tire)
                   .Where(p => p.Id == 1);

见:Entity Framework - Loading Related Entities

【讨论】:

  • 比我快一分钟 :)
  • @Habib:每天都是上学日 :) 非常感谢。作为附加信息:有必要添加using System.Data.Entity; 以避免Cannot convert lambda expression to type 'string' because it is not a delegate type 错误。
【解决方案2】:

您正在寻找Include() 方法。

List<Motorbike> motorbikes = _context.Motorbike
    .Include(p => p.Engine)
    .Include(p => p.Tire)
    .Where(p => p.Id == 1)
    .ToList();

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 2018-07-19
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2016-12-10
    • 2014-09-17
    相关资源
    最近更新 更多