我具有以下架构:
我的实体并在其中映射(0..1:1):
public class AspNetUser
{
//.....
public virtual Manager Manager { get; set; }
public virtual Driver Driver { get; set; }
}
public partial class Driver
{
public int Id { get; set; }
//....
public virtual AspNetUser AspNetUser { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Manager
{
public int Id { get; set; }
//....
public virtual AspNetUser AspNetUser { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Nickname { get; set; }
}
public class AspNetUserMap : EntityTypeConfiguration<AspNetUser>
{
public AspNetUserMap()
{
this.HasKey(dp => dp.Id);
this.Property(p => p.UserName).IsRequired().HasMaxLength(256);
this.HasIndex(p => p.UserName).IsClustered(false).IsUnique();
this.HasOptional(c => c.Driver)
.WithOptionalPrincipal(a => a.AspNetUser)
.Map(m => m.MapKey("AspNetUserId"));
this.HasOptional(c => c.Manager)
.WithOptionalPrincipal(a => a.AspNetUser)
.Map(m => m.MapKey("AspNetUserId"));
现在,我需要从AspNetUser获取所有用户,但要使用他们的FN / LN。要获取FN / LN,我应该检查用户角色,然后致电驱动程序或管理器。
我有以下代码:
List<ChatUserDomain> returnedUsers = new List<ChatUserDomain>();
var users = (from i in db.AspNetUsers
.Include(path => path.Driver)
.Include(path => path.Manager)
.Include(path => path.AspNetRoles)
where i.CompanyId == db.AspNetUsers.Where(p => p.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault().CompanyId
select new
{
AspNetUser = i,
Username = i.UserName,
....
}
).ToList();
foreach (var user in users)
{
returnedUsers.Add(new ChatUserDomain()
{
UserId = user.AspNetUser.Id,
Name = GetNameByUser(user.AspNetUser),
...
});
}
return returnedUsers;
和GetNameByUser方法:
private string GetNameByUser(AspNetUser aspNetUser)
{
IProfile profile = GetProfileByUser(aspNetUser);
if (!String.IsNullOrWhiteSpace(profile.FirstName) && !String.IsNullOrEmpty(profile.LastName))
{
return (GetFirstLettersOfFullName(profile.FirstName, profile.LastName));
}
else
{
return (aspNetUser.UserName.Substring(0, 2));
}
}
private IProfile GetProfileByUser(AspNetUser aspNetUser)
{
IProfile profile = null;
var role = aspNetUser.AspNetRoles.FirstOrDefault().Name;
if (role.Equals(Domain.StaticStrings.RoleStaticStrings.ROLE_DRIVER))
profile = aspNetUser.Driver;
else
profile = aspNetUser.Manager;
return profile;
}
它可以工作,但是会创建其他user.Count对DB的调用。如何对EF说“父请求中的负载管理器和驱动器数据”?