【问题标题】:How do I include the dependent entities of an inherited entity with entity framework core that uses Discriminator column?如何将继承实体的依赖实体包含在使用鉴别器列的实体框架核心中?
【发布时间】:2017-05-11 22:30:52
【问题描述】:

给定以下具有继承的模型:

public class Credential { ... }

public class LocationCredential: Credential {
    ...
    public long LocationId {get; set;}
    public Location Location {get; set;}
}

public class EducationCredential: Credential {
    ...
    public long SchoolId {get; set;}
    public Location School {get; set;}
}

public class School { ... }
public class Location { ... }

实体框架核心仅创建一个带有Discriminator 列的Credentials 表来标识数据库中的继承类。

查询凭据时如何包含依赖实体? 我想做这样的事情:

var cred = await context.Credentials
    .Where( c => c.CredentialId == 123)
    .Include(c => c.Location) // cannot do these beacause they are not 
    .Include(c => c.School)  // properties of Credential class
    .FirstOrDefaultAsync();

我不想对每个继承的类进行单独的查询,然后返回非空类。不想要这些:

 var cred = await context.EducationCredentials
        .Where( c => c.CredentialId == 123)
        .Include(c => c.School)  
        .FirstOrDefaultAsync();
   if (cred == null) {
       // try same thing with LocationCredentials
   }
   ...

【问题讨论】:

    标签: entity-framework linq asp.net-core entity-framework-core


    【解决方案1】:

    我最终这样做了;我仍然不喜欢它,因为它需要两次调用数据库;

            var cred =  await _context.Credentials
                .Where(c => c.CredentialId == credentialId)
                .FirstOrDefaultAsync();
    
            if (cred.GetType() == typeof(LocationCredential)) {
                return await _context.LocationCredentials
                    .Where(e => e.CredentialId == credentialId)
                    .Include(e => e.Location)
                    .FirstOrDefaultAsync();
            }
    
            ...
    

    【讨论】:

      【解决方案2】:
      [NotMapped]
      

      公共类LocationCredential:凭据 {

      ...
      public long LocationId {get; set;}
      public Location Location {get; set;}
      

      }

      像这样在模型上使用 [NotMapped] 属性。

      【讨论】:

      • [NotMapped] 用于不通过实体框架在数据库中创建模型/列。这根本不是我想要做的。
      猜你喜欢
      • 2013-12-04
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      相关资源
      最近更新 更多