0

我有一个名为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; }

这两个列TraineeIDTrainerID将与表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 中映射两个具有相同主键的外键?

4

2 回答 2

2

像这样的东西:

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());
          ......
     }
     ....
}
于 2012-09-04T10:46:07.133 回答
-1

如果您使用的是 MVC3 或 4,那么您可以使用实体框架映射来做同样的事情,这反过来会生成所需的类。您可以使用模型浏览器来执行相同的操作。

你必须做的:

创建表 在表中创建 PK 和 FK 约束 右键单击​​项目中解决方案资源管理器中的模型文件夹选择添加新项,从“数据”类别中选择 ADO.Net EF 4.x/5.x 单击确定将打开一个向导,提供所需的参数,在途中选择您需要的表格。完成后,它将简单地在 .Edmx 的上下文文件中创建一个 .Edmx 文件,我

于 2012-09-04T11:26:55.170 回答