简体   繁体   English

EFCore,多对多,DB First,导航属性不起作用

[英]EFCore, many-to-many, DB First, navigation properties not working

I am trying to map to an existing database. 我正在尝试映射到现有数据库。 When I use the below code and pull a list of results for a given entity, I get back the results I expect. 当我使用下面的代码并为给定实体提取结果列表时,我会得到我期望的结果。

However, when I attempt to add .Include(x => x.Book) to a simple list query against the UserBook table, my result set returns empty. 但是,当我尝试将.Include(x => x.Book)到针对UserBook表的简单列表查询时,我的结果集返回空。

[Table("User")]
public class User
{
    [Key]
    public Guid UserId { get; set; }
    public string UserName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("Book")]
public class Book
{
    [Key]
    public Guid BookId { get; set; }
    public string BookName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("UserBook")]
public class UserBook
{
    public Guid UserId { get; set; }
    public Guid BookId { get; set; }
    public int PermissionMask { get; set; }
    public bool Deleted { get; set; }

    // Ref
    public User User { get; set; }
    public Book Book { get; set; }
}

I'm following the instructions layed out here: http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration 我按照这里的说明进行操作: http//www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

To better illustrate the issue, here are the queries I'm using: 为了更好地说明问题,以下是我正在使用的查询:

// Returns 1,000+ rows.
_context.UserBooks.ToList();

// Returns 1 row
_context.UserBooks
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks
    .Include(x => x.Book)
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks.Include(x => x.Book).ToList();

I think EF would complain that UserBook entity does not have keys defined, not sure how you got it to work. 我认为EF会抱怨UserBook实体没有定义键,不知道你是如何让它工作的。 But to make the include work I believe you need to be explicit on the composite key. 但是为了使包含工作我相信你需要明确复合键。 Try adding the following to your DbContext class: 尝试将以下内容添加到DbContext类:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<UserBook>(e => e.HasKey(c => new { c.UserId, c.BookId }));
}

Your mapping indicates a non-nullable foreign key (so EF will generate an inner join in the query). 您的映射表示不可为空的外键(因此EF将在查询中生成内部联接)。 Try changing datatype on the foreign keys from Guid to Guid? 尝试将外键上的数据类型从Guid更改为Guid? and try again. 然后再试一次。

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

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