【发布时间】:2016-09-26 17:08:09
【问题描述】:
我正在尝试使用 Entity framework 6.1 来构建具有数据库优先方法的应用程序。
我很困惑如何在不使用默认 Key aka Id 作为本地属性的情况下建立一对多关系。
我有以下两个模型,首先
public class UserToClient
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("ViewClient")]
public int ClientId { get; set; }
[ForeignKey("Team")]
public int DefaultTeamId { get; set; }
public bool IsActive { get; set; }
public virtual ViewClient ViewClient { get; set; }
public virtual Team Team { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
这是我的第二个模型
public class Team
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public bool IsActive { get; set; }
public string Name { get; set; }
[ForeignKey("ViewClient")]
public int ClientId { get; set; }
public virtual ICollection<ViewClient> ViewClients { get; set; }
public virtual UserToClient UserToClient { get; set; }
}
在我的UserToClient 模型中,我想创建一对多关系“一个UserToClient 有很多Team”
有了最终结果,我希望能够做这样的事情
using(var connection = new AppContext())
{
var userToClients = connection.UserToClients
.Include(x => x.Team)
.Include(x => x.Teams)
.ToList();
//Do something with userToClients
//Do something with userToClients.Team
//Do something with each team
foreach(var team in userToClients.Teams)
{
//Do something with 'team'
}
}
如果我要在“实体外部”手动编写查询,我会这样做
SELECT *
FROM [UserToClient] AS r
LEFT JOIN [Team] AS t ON t.ClientId = r.ClientId
问题
关系需要指向一个名为ClientId 的属性,而不是主键Id。
实体当前正在生成这样的查询,我希望能够将Id 更改为ClientId。
SELECT *
FROM [UserToClient] AS r
LEFT JOIN [Team] AS t ON t.Id = r.ClientId
了解Id 是主键很重要,但在这种情况下,我想加入一个不是主键的键。
我该如何解决这个问题?
尝试
我试图通过像这样覆盖上下文类中的OnModelCreating 方法来解决这个问题
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Team>()
.HasRequired(x => x.UserToClient)
.WithMany(x => x.Teams)
.HasForeignKey(f => f.ClientId);
}
我需要一种方法来告诉关系本地属性是ClientId 而不是Id
我该如何解决?
【问题讨论】:
标签: c# asp.net-mvc entity-framework entity asp.net-mvc-5.2