簡體   English   中英

在具有一對多關系的實體中同時插入數據

[英]Insert data simultaneously in entity having one to many relationship

我有兩個實體:“學生”和“注冊”具有一對多關系。 實體看起來像

public class Student{
 [Key]
 public int Studentid {get; set;}
 public string fname{get; set;}
 public string lname{get; set;}
 public virtual ICollection<Enrollement> Enrollement_E{ get; set; }
 }

 public class Enrollement{
 [Key]
 public int EnrolId {get; set;}

 [ForeignKey("Studentid ")]
 public int Student{get; set;}
 public string kk{get; set;}
 public virtual Student Student_E { get; set; }
 }

Studentid是自動遞增的主鍵,在注冊表中用作外鍵。 我正在嘗試將數據插入兩個表中。 如果其中一個失敗,則兩個插入都不應提交。 因此,我有以下代碼。

try{
  repository.stu.insert(new student{fname = "fname", lname="lname"});
  repository.enr.insert(new Enrollement{student=???, kk="test"});
}
finally{
  repository.save();
}

如果尚未保存數據,我應該如何將外鍵傳遞給注冊記錄。 還是有另一種方法?

代替分配外鍵,而是分配整個對象:

try{
  var student = new student(){fname = "fname", lname="lname"};
  repository.stu.insert(student);
  repository.enr.insert(new Enrollement(){Student_E = student});
}
finally{
  repository.save();
}

這樣,當student獲得新密鑰時,它將自動保存到注冊中。

您不需要分別保存這兩個對象,只需在保存調用中即可實現

public class Student{
 [Key]
 public int Studentid {get; set;}
 public string fname{get; set;}
 public string lname{get; set;}
 public virtual ICollection<Enrollement> Enrollement_E{ get; set; }
 }

 public class Enrollement{
 [Key]
 public int EnrolId {get; set;}
 [ForeignKey("Studentid ")]
 public int Student{get; set;}
 public string kk{get; set;}
 public virtual Student Student_E { get; set; }
 }

在連接的OnModelCreating方法內,定義類似的關系,它將確保您具有Student對象,其相關或子對象時,即也將保存Enrollements

modelBuilder.Entity<Student>()
                .HasMany(c => c. Enrollement_E)
                .WithOne(e => e. Student_E);
modelBuilder.Entity<Enrollement>().Ignore(x => x. Student_E);

現在您的代碼應如下所示

try{
     student _student = new student{fname = "fname", lname="lname"};
     _student.Enrollement_E = new List< Enrollement>();
     _student.Enrollement_E.add(new Enrollement{student=???, kk="test"});
     repository.stu.insert(_student); 
}
finally
{
     repository.save();
}

這是使用Entity Framework Core完成的最后一件事,遵循約定,您還需要更改外鍵字段

public int Student{get; set;} to  public int StudentId{get; set;}

EF輕松處理外鍵以將數據插入到多個相關表中。 如果要同時在兩個表中插入數據,則可以使用以下代碼進行插入:

   student st = new student 
    {
      fname = "fname",
      lname= "lname",

      Enrollement_E=new List<Enrollement>
      {
        new Enrollement{kk="something"}
      }
    };

    repository.student.Add(st);
    repository.SaveChanges();

EF本身為第二張表做外鍵

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM