插入许多对许多不能使用Entity Framework的记录 [英] Insert records in many to many not working with Entity Framework
问题描述
这个主题有很多问题,我尝试了许多答案,现在我不知道为什么我的代码不工作。
请帮助我!
这是代码:
class Program
{
static void Main(string [] args)
{
MyContext db = new MyContext();
var st1 = new Student(){Name =Joe};
var c1 = new Course(){Name =Math};
db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
db.SaveChanges();
}
}
public class Student
{
public Student()
{
课程= new HashSet< Course>();
}
public int Id {get;组; }
public string Name {get;组; }
public virtual ICollection< Course>课程{get;组; }
}
public class课程
{
public int Id {get;组; }
public string Name {get;组; }
public virtual ICollection< Student>学生{get;组; }
}
public class MyContext:DbContext
{
public DbSet< Student>学生{get;组; }
public DbSet< Course>课程{get;组;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< Student>()
.HasMany(p => p.Courses)
.WithMany(d => d.Students)
.Map(t =>
{
t.MapLeftKey(studentId);
t.MapRightKey (courseid);
t.ToTable(StudentCourse);
});
base.OnModelCreating(modelBuilder);
}
}
编辑:像sugested ,我初始化了课程:
public Student()
{
课程=新的HashSet<课程和GT;();
}
现在我在db.SaveChanges();
保存不暴露其关系属性的实体时出错。 EntityEntries属性将返回null,因为单个实体不能被识别为异常的源。通过在您的实体类型中暴露外键属性,可以更容易地处理异常处理。有关详细信息,请参阅InnerException。
你显然正在尝试添加一个新的code>学生到数据库,并将其与现有 课程
相关联。问题是你附上一个新的课程
实体到上下文没有正确的主键。
它当然是在这里使用所谓的存根实体的好主意,是因为它保存了往返数据库以获取现有的课程
,但主要EF需要密钥来创建正确的关联记录。这是您在课程 c> stub中需要设置的唯一财产:
var st1 = new Student(){Name =Joe};
var c1 = new Course(){CourseId = 123};
db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
如果要添加新课程和新学生,您应该添加
两者:
db.Courses.Add(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
I want to insert 2 new records in their tables and also to create the relation many to many.
There are a lot of questions with this topic, I tried many of the answers and now I have no idea why my code is not working.
Please help me!
This is the code:
class Program
{
static void Main(string[] args)
{
MyContext db = new MyContext();
var st1 = new Student() { Name = "Joe" };
var c1 = new Course() { Name = "Math" };
db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
db.SaveChanges();
}
}
public class Student
{
public Student()
{
Courses = new HashSet<Course>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany(p => p.Courses)
.WithMany(d => d.Students)
.Map(t =>
{
t.MapLeftKey("studentId");
t.MapRightKey("courseid");
t.ToTable("StudentCourse");
});
base.OnModelCreating(modelBuilder);
}
}
Edit: Like sugested, I initialized the Courses:
public Student()
{
Courses = new HashSet<Course>();
}
and now I get this error on db.SaveChanges();
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
You're apparently trying to add a new Student
to the database and associate it to an existing Course
. The problem is that you attach a new Course
entity to the context without a proper primary key.
It certainly is a good idea to use a so-called stub entity here, because it saves a roundtrip to the database to fetch an existing Course
, but the primary key is required for EF to create a correct association record. It's even the only property you need to set in this Course
stub:
var st1 = new Student() { Name = "Joe" };
var c1 = new Course() { CourseId = 123 };
db.Courses.Attach(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
If you want to add a new course and a new student, you should Add
both of them:
db.Courses.Add(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);
这篇关于插入许多对许多不能使用Entity Framework的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!