如何将记录首先插入到许多代码Approch中 [英] How to Insert Records into many to many code first Approch
本文介绍了如何将记录首先插入到许多代码Approch中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的实体类
My entity class
public class person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Course> courses { get; set;}
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public virtual ICollection<person> Persons { get; set; }
}
我的上下文类代码
My Context class code
public class Context : DbContext
{
public Context()
: base("test")
{ }
public DbSet<person> Persons { get; set; }
public DbSet<Course> Courses { get; set; }
modelBuilder.Entity<Course>()
.HasMany(c => c.Persons)
.WithMany(p => p.courses)
.Map(m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
}
);
当我尝试将对象添加到人员类的课程集合时
i得到错误,如此对象引用未设置为对象的实例。 br />
和我的代码在这里:
When I try add Objects to course Collection which is in persons class
i am getting error like this Object reference not set to an instance of an object.
and My Code is here:
using (Context db = new Context())
{
Course stoptalk = new Course();
Course ruby = new Course();
Course rails = new Course();
stoptalk.Title = "Stoptalk";
ruby.Title = "Ruby";
rails.Title = "Rails";
db.Courses.Add(stoptalk);
db.Courses.Add(ruby);
db.Courses.Add(rails);
person john = new person();
john.FirstName = "John";
john.LastName = "Meclian";
if (john.courses == null)
{
john.courses.Add(stoptalk);
john.courses.Add(rails);
db.Persons.Add(john);
db.SaveChanges();
}
}
推荐答案
这部分代码会给你这个问题
This part of the code will give you this problem
if (john.courses == null)
{
john.courses.Add(stoptalk);
john.courses.Add(rails);
db.Persons.Add(john);
db.SaveChanges();
}
因为如果 john.courses == null
为真,那么添加
操作无法执行,因为没有创建 john.courses
的实例。
您需要做的是正确初始化会员课程
。
示例:
because if john.courses == null
is true, the Add
operation cannot be executed as no instance of john.courses
has been created.
What you need to do is to initialize the member courses
properly.
Example:
public class person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Course> courses { get; set;}
// Default constructor
public person()
{
PersonId = 0;
FirstName = "";
LastName = "";
courses = new List<Course>;
}
}
</course>
然后更改if语句:
Then change the if-statement:
if (john.courses.Count == 0)
{
...
}
这篇关于如何将记录首先插入到许多代码Approch中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文