最初,我的基本内容Client
包括:
public class Client : Entity
{
[Required]
public string Name { get; set; }
}
我User
的 s 以及通常的Name
字段等具有Client
:
public class User : Entity
{
[Required, MinLength(4), Display(Name = "Username")]
public string Username { get; set; }
[Required, MinLength(2), Display(Name = "First Name")]
public string FirstName { get; set; }
[Required, MinLength(2), Display(Name = "Last Name")]
public string LastName { get; set; }
[Required, EmailAddress]
public string Email { get; set; }
...
[Required]
public virtual Client Client { get; set; }
}
我的Get
方法:
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string[] includeProperties = null)
{
IQueryable<TEntity> query = dbSet;
if (includeProperties != null)
query = includeProperties.Aggregate(query, (q, s) => q.Include(s));
query = query.Where(x => !x.Deleted);
if (filter != null)
query = query.Where(filter);
return orderBy != null ? orderBy(query).ToList() : query.ToList();
}
这一切都很好。所以,关于问题:它实际上与我的客户有关,因为为AccountManager
(即 a User
)添加了一个附加属性,它不喜欢我。
public class Client : Entity
{
[Required]
public string Name { get; set; }
[Required]
public CompanyType CompanyType { get; set; }
[Required]
public ClientStatus Status { get; set; }
[SomethingInHere?]
public virtual User AccountManager { get; set; }
public DateTime? AccessFrom { get; set; }
public DateTime? AccessTo { get; set; }
public DateTime? ClosedDate { get; set; }
}
我已经INCLUDE_STRING
为Get
s 添加了“AccountManager”,甚至最近尝试使用各种ForeignKey
/数据注释,但无法让它连同Required
它一起拉出 AccountManager 。User
有了这个,我认为这是我无法再拔出任何User
s 的部分原因,如果不是全部原因的话。
简而言之,我对 EF 关系处理的掌握有些有限,而且我今天的谷歌搜索能力似乎还达不到标准。
许多User
s 到 a Client
。每个User
人一个。为什么这对我来说这么难?AccountManager
Client
编辑:四舍五入的答案。
在模型构建器部分中添加:
modelBuilder.Entity<User>()
.HasRequired(x => x.Client)
.WithMany(x => x.Users);
modelBuilder.Entity<Client>()
.HasOptional(x => x.AccountManager);
并更改Client
以包含用户列表:
public class Client : Entity
{
[Required]
public string Name { get; set; }
[Required]
public CompanyType CompanyType { get; set; }
[Required]
public ClientStatus Status { get; set; }
public virtual IList<User> Users { get; set; }
public virtual User AccountManager { get; set; }
public DateTime? AccessFrom { get; set; }
public DateTime? AccessTo { get; set; }
public DateTime? ClosedDate { get; set; }
}
这让 EF 很高兴能够正确地把它全部拿出来。