2015-04-28 24 views
0

找对象我使用实体框架代码第一次和我有三个表(例如):EF和LINQ:从数据库细胞

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(其中只存储数字 - 引擎,而不是整个对象)和Tire_Id(其中只存储数字 - 轮胎,而不是整个对象)。

我知道如何插入数据 - 只要创建新的摩托车对象,并保存在他的字段数据(EngineTire领域我保存整个对象不仅ID),并使用.Add()方法从我的背景。

但如何得到摩托车id是(例如)1行的数据?

我已经试过这样的事情:

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

但始终我得空了EngineTire场视频(Id和PRODUCENT正确填写)。

+0

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

回答

2

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

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

参见:Entity Framework - Loading Related Entities

+1

打了我一分钟:) –

+0

@Habib:每天都是上学的日子:)非常感谢。作为附加信息:有必要添加'using System.Data.Entity;'以避免'不能将lambda表达式转换为'string'类型,因为它不是委托类型错误。 –

1

您正在寻找的Include()方法。

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