简体   繁体   English

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

[英]Entity Framework: Trying to query an entity with a foreign key relationship

Models: 楷模:

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
}

Running this linq query: 运行此linq查询:

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

yields this sql query: 产生以下SQL查询:

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

It's weird that it decided not to camel case the association column like it did with the other properties. 奇怪的是,它决定不像在其他属性中那样对骆驼案进行命名。 Is there some reason for this? 有什么原因吗?

In any case, I added mapping code to try and fix it: 无论如何,我都添加了映射代码以尝试修复它:

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

Unfortunately, querying with linq produces this query: 不幸的是,使用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

It looks a bit better, but obviously doesn't work still because my table has the column GroupId and not Group_Id. 它看起来好一些,但显然仍然无法正常工作,因为我的表具有列GroupId而不是Group_Id。 Does anyone know what's going on here or how to fix it? 有谁知道这里发生了什么或如何解决?

Since the mapping User-Group is n - 1 the mapping should be: 由于映射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 created the Group_Id column itself for the 1-n association it inferred from your class model, while GroupId was added because of the 1:1 association you mapped yourself. EF为从类模型中推断出的1-n关联本身创建了Group_Id列,而由于您自己映射的1:1关联而添加了GroupId

Or you can write it as follow 或者你可以写成如下

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; }
}

Group_Id cloumn is created automatically when not define foreignKey property. 未定义foreignKey属性时,将自动创建Group_Id cloumn。

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

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