我正在尝试使用Entity framework 6.1来构建一个使用数据库第一种方法的应用程序。
我很困惑如何构建一对多关系,而不使用默认的Key
又名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
我该如何解决?