在实体框架模型中为ICollection定义外键
本文关键字:ICollection 定义 实体 框架 模型 | 更新日期: 2023-09-27 18:01:06
如何在Entity Framework 6
中定义哪些列将用于引用ICollection<>
中的数据?
例如,我们有一个简单的用户信息关系,如果我可以从更新或创建信息的用户那里获得所有信息:
public class User
{
public int UserId
{
get;
get;
}
// Here is the problem, how to define that EF
// Has to use the CreateUser column
public virtual ICollection<User> User_CreateUser
{
get;
set;
}
// Here is the problem, how to define that EF
// Has to use the UpdateUser column
public virtual ICollection<User> User_UpdateUser
{
get;
set;
}
}
public class Information
{
public int InfoId
{
get;
set;
}
public int CreateUser
{
get;
set;
}
public int UpdateUser
{
get;
set;
}
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("CreateUser")]
public virtual User User_CreateUser
{
get;
set;
}
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("UpdateUser")]
public virtual User User_UpdateUser
{
get;
set;
}
}
但我不知道,如何绘制地图。对于简单的外键,它比注释更容易。
我首先使用数据库,但自己生成模型。(除了ICollection<>
.之外,它的效果还不错
谢谢!
您已经将第二个外键标记为User
,但它应该是int
。
public int UpdateUser { get; set; }
试试这个:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace Test
{
public class User
{
public int UserId { get; set; }
public virtual ICollection<User> User_CreateUser { get; set; }
public virtual ICollection<User> User_UpdateUser { get; set; }
}
public class Information
{
public int InfoId { get; set; }
public int CreateUser { get; set; }
public int UpdateUser { get; set; }
[ForeignKey("CreateUser")]
public virtual User User_CreateUser { get; set; }
[ForeignKey("UpdateUser")]
public virtual User User_UpdateUser { get; set; }
}
}