0

楷模:

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

4

2 回答 2

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"));

EFGroup_Id为它从您的类模型中推断出的 1-n 关联创建了列本身,而GroupId由于您自己映射的 1:1 关联而被添加。

于 2013-07-24T20:41:17.087 回答
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; }
}

Group_Id cloumn 在未定义 foreignKey 属性时自动创建。

于 2013-07-25T01:40:42.120 回答