实体框架:尝试查询具有外键关系的实体

时间:2013-07-24 18:02:24

标签: c# entity-framework-4

型号:

public class User
{
    public int Id {get; set;}
    public int SomeProperty {get; set;}
    public virtual Group Group { get; set; }
}

public class Group {
{
    public int Id {get; set;}
    // other properties
}

运行此linq查询:

myContext.Users.Where(u => u.SomeProperty = 4);

产生这个SQL查询:

select
    extent1.Id as Id
    extent1.SomeProperty as SomeProperty
    extent1.Group_Id as Group_Id
from
    dbo.Users as extent1

奇怪的是,它决定不像其他属性一样使用关联列。这有什么理由吗?

无论如何,我添加了映射代码来尝试修复它:

var entity = modelBuilder.Entity<User>();
entity.HasRequired( a => a.Group )
    .WithRequiredDependent()
    .Map( a => a.MapKey( "GroupId" ) );

不幸的是,使用linq查询产生了这个查询:

select
    extent1.Id as Id
    extent1.SomeProperty as SomeProperty
    extent1.GroupId as GroupId
    extent1.Group_Id as Group_Id
from
    dbo.Users as extent1

它看起来好一点,但显然不起作用,因为我的表有GroupId列而不是Group_Id。有谁知道这里发生了什么或如何修复它?

2 个答案:

答案 0 :(得分:1)

由于映射User-Group为n - 1,因此映射应为:

var entity = modelBuilder.Entity<User>();
entity.HasRequired(a => a.Group)          // user has one Group
      .WithMany()                         // Group has many Users
      .Map( a => a.MapKey("GroupId"));

EF为您从类模型推断的1-n关联创建了Group_Id列本身,而由于您自己映射的1:1关联,因此添加了GroupId

答案 1 :(得分:0)

或者您可以按照以下方式编写

public class User
{
   public int Id {get; set;}
   public int SomeProperty {get; set;}

   [ForeignKey("Group")] 
   public int GroupId {get;set;}
   public virtual Group Group { get; set; }
}

未定义foreignKey属性时会自动创建Group_Id列。