简体   繁体   English

在许多不使用Entity Framework的情况下插入记录

[英]Insert records in many to many not working with Entity Framework

I want to insert 2 new records in their tables and also to create the relation many to many. 我想在其表中插入2条新记录,并创建多对多关系。

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(); 现在我在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. EntityEntries属性将返回null,因为无法将单个实体标识为异常的来源。 Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. 通过在实体类型中公开外键属性,可以简化保存时的异常处理。 See the InnerException for details. 有关详细信息,请参见InnerException。

You're apparently trying to add a new Student to the database and associate it to an existing Course . 您显然正在尝试向数据库中添加一个新Student并将其与现有 Course相关联。 The problem is that you attach a new Course entity to the context without a proper primary key. 问题在于您将新的Course实体附加到上下文,而没有正确的主键。

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. 在这里使用所谓的存根实体当然是个好主意,因为它可以保存到数据库的往返行程以获取现有的Course ,但是EF必须使用主键才能创建正确的关联记录。 It's even the only property you need to set in this Course stub: 它甚至是您需要在此Course存根中设置的唯一属性:

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: 如果要添加新课程和新学生,则应同时Add它们:

db.Courses.Add(c1);
st1.Courses.Add(c1);
db.Students.Add(st1);        

Your code isn't initialising the ICollection object in either class. 您的代码没有在任何一个类中初始化ICollection对象。

public class Student
{
    private Student()
    {
        Courses = new List<Course>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

Edit 编辑

Try changing your modelBuilder code to the following 尝试将您的modelBuilder代码更改为以下内容

modelBuilder.Entity<Student>()
            .HasMany<Course>(s => s.Courses)
            .WithMany(c => c.Students)
            .Map(cs =>
                    {
                        cs.MapLeftKey("StudentRefId");
                        cs.MapRightKey("CourseRefId");
                        cs.ToTable("StudentCourse");
                    });

Code sample taken directly from: 代码示例直接取自:

http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM