【问题标题】:Entity Framework: Trying to query an entity with a foreign key relationship实体框架:尝试查询具有外键关系的实体
【发布时间】:2013-07-25 09:40:42
【问题描述】:

型号:

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。有谁知道这里发生了什么或如何解决它?

【问题讨论】:

标签: c# entity-framework-4


【解决方案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 列,而添加了 GroupId 是因为您自己映射了 1:1 关联。

【讨论】:

    【解决方案2】:

    也可以这样写

    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 cloumn。

    【讨论】:

      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2018-09-09
      相关资源
      最近更新 更多