我试图在我的模型中自我引用一个表来获取我的User
实体的一些细节
我有一个看起来像这样的课程:
public class User
{
[Key]
[Column("recid")]
public int Id { get; set; }
[Column("givenname")]
public string FirstName { get; set; }
[Column("sn")]
public string LastName { get; set; }
[Column("mail")]
public string Email { get; set; }
[Column("managerEmail")]
public string LineManagerEmail { get; set; }
public string LineManagerFirstName { get; set; }
public string LineManagerLastName { get; set; }
}
如何对此进行映射,以便在返回User
时从同一个表中检索LineManagerFirstName
和LineManagerLastName
,并加入LineManagerEmail?
例如,我预计SQL会像:
SELECT
user.recid,
user.givenName,
user.sn,
user.mail,
user.managerEmail,
manager.givenName as lineManagerFirstName,
manager.givenName as lineManagerLastName,
FROM user
INNER JOIN user AS manager
ON user.managerEmail = manager.mail
在我的Context类中,我知道我需要覆盖OnModelCreating方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().
}
...但是对EF来说是新手,这就是我陷入困境的地方!
答案 0 :(得分:0)
如果您使用视图,则可能无法更新用户,因为视图是只读的。
您应该根据表创建实体,然后根据您的需要进行查询,并使用类似
的查询实现UserExtendedvar q = from
u in Users
select
new UserExtended {
Id = u.Id,
/* .... */
LineManagerFirstName = u.Manager.FirstName
/* .... */
}
或更精细的查询,如果是没有PK的自我加入。
var q =
from u in Users
join m in Users on u.Email equals m.Email
select
new UserExtended {
Id = u.Id,
/* .... */
LineManagerFirstName = m.FirstName
/* .... */
}
将为您提供以下SQL(字段名称不匹配,因为我使用我的架构之一)
SELECT
[Extent1].[idUtilisateur] AS [idUtilisateur],
[Extent2].[Email] AS [Email]
FROM [dbo].[tableU] AS [Extent1]
INNER JOIN [dbo].[tableU] AS [Extent2] ON
([Extent1].[Email] = [Extent2].[Email])
OR (([Extent1].[Email] IS NULL) AND ([Extent2].[Email] IS NULL))