简体   繁体   中英

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:

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

yields this sql query:

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:

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. 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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