我需要以某种方式显式地忽略复杂类型的“深度”导航属性,或显式地告诉EF如何加入
我正在简单地选择用户并映射到平面视图模型(显然我已经为ProjectTo设置了相关的映射):
from django.shortcuts import render
from django.http import HttpResponse
from .models import Courses
def homepage(request):
cos = Courses.objects.all()
context={ 'courses': cos }
return render(request, "main/home.html", context)
像这样覆盖OnModelCreating方法适用于这种情况,但是显然将一直排除OwnerPerson,我们只想排除 当从数据库中选择User实体并将其映射到UserModel时使用它:
return await DataContext.Users
.ProjectTo<UserModel>()
.ToListAsync();
public class User {
public int PersonId { get; set; }
public Person Person { get; set; }
}
public class Person {
public int Id { get; set; }
public int DeptartmentId { get; set; }
public Department Department { get; set; }
}
public class Department {
public int Id { get; set; }
public int DeptartmentHeadId { get; set; }
public Person DepartmentHead { get; set; }
}
public class UserSummary
{
public Guid Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string DepartmentName { get; set; }
}
我需要做类似的事情:
builder.Entity<Department>().Ignore(x => x.DepartmentHead);
使用SQL事件探查器,您可以看到它在部门上创建了意外连接:
builder.Entity<User>().Ignore(x => x.Person.Department.DepartmentHead);
我想要的是:
SELECT * FROM [Users] AS [x]
INNER JOIN [dbo].[People] AS [x.Person]
ON [x].[PersonId] = [x.Person].[Id]
LEFT JOIN [Departments] AS [x.Person.Department]
ON [x.Person].[Id] = [x.Person.Department].[DeptartmentHeadId]
答案 0 :(得分:1)
我需要做的就是告诉EF部门有人员(因此确定关系映射):
public class Department {
public int Id { get; set; }
public int DeptartmentHeadId { get; set; }
public Person DepartmentHead { get; set; }
[InverseProperty(nameof(Person.Department))]
public IList<Person> People { get; set; } = new List<Person>();
}