如何将继承实体的依赖实体包含在使用Discriminator列的实体框架核心中?

时间:2017-05-11 10:44:21

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

给出以下带继承的模型:

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 { ... }

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

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

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

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

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

2 个答案:

答案 0 :(得分:0)

我最终做到了这一点;我仍然不喜欢它,因为它需要两次调用db;

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

        ...

答案 1 :(得分:0)

[NotMapped]

public class LocationCredential:Credential {

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

}

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