[英]How can I map two different foreign key with same primary key in different table?
我有一個名為EnrollTrainee的表。 我的EnrollTrainee模型類中有以下列:
[Key]
public int id { get; set; }
public int TraineeID { get; set; }
public int TrainerID { ![enter image description here][1]get; set; }
public virtual CreateUsers user_userid { get; set; }
public virtual CreateUsers user_id { get; set; }
public DateTime dt { get; set; }
這兩個列TraineeID和TrainerID將與表CreateUser中的 User_id列進行映射。
這是CreateUser模型類
public class CreateUsers
{
[Key]
public int User_Userid { get; set; }
[Required]
[Display(Name="Enter User Name")]
public string User_name { get; set; }
[Required]
[Remote("IsDomainIDExist", "Account", ErrorMessage = "Domain ID Already Exist")]
[Display(Name = "Enter Domain ID")]
public string User_username { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Enter Password")]
public string User_password { get; set; }
[Required]
[Display(Name = "Enter Department")]
public string User_department { get; set; }
[Required]
[Remote("IsEmployeeIDExist", "Account", ErrorMessage = "Domain ID Already Exist")]
[Display(Name = "Enter Employee ID")]
public string User_employeeid { get; set; }
[Required]
[Display(Name="Select Role Type")]
public int RoleID { get; set; }
[Display(Name="Enable?")]
public bool User_Enable { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Date Time")]
public DateTime dt { get; set; }
public virtual RoleModel Role { get; set; }
}
如何在EF CF中映射兩個具有相同主鍵的外鍵?
像這樣:
public class EnrollTrainee
{
[Key]
public int id { get; set; }
public int TraineeID { get; set; }
public virtual CreateUser Trainee { get; set; }
public int TrainerID { get; set; }
public virtual CreateUser Trainer { get; set; }
public DateTime dt { get; set; }
}
internal class EnrollTraineeConfiguration:EntityTypeConfiguration<EnrollTrainee>
{
public EnrollTraineeConfiguration()
{
ToTable("EnrollTrainee");
Property(c => c.dt).HasColumnName("dt");
Property(c => c.TraineeID).HasColumnName("TraineeID");
Property(c => c.TrainerID).HasColumnName("TrainerID");
HasKey(c => c.id);
HasRequired(c => c.Trainee).WithMany().HasForeignKey(c=>c.TraineeId);
HasRequired(c => c.Trainer).WithMany().HasForeignKey(c => c.TrainerId);
}
}
public class Context: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new EnrollTraineeConfiguration());
......
}
....
}
如果您使用的是MVC3或4,則可以使用Entity Framework映射執行相同的操作,這將生成所需的類。 您可以使用模型瀏覽器執行相同的操作。
您要做的是:
創建表在表中創建PK和FK約束右鍵單擊項目中解決方案資源管理器中的“模型”文件夾,選擇“添加新項”,從“數據”類別中選擇ADO.Net EF 4.x / 5.x,單擊“確定”將打開一個向導,提供所需的參數,在選擇要查詢的表的方式上。 完成后,它將僅在.Edmx的上下文文件中創建一個.Edmx文件,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.