Entity framework core 添加具有复杂类型属性的实体
我正在尝试在我的数据库中添加学生实体,如下所示:Entity framework core 添加具有复杂类型属性的实体,entity-framework-core,asp.net-core-webapi,Entity Framework Core,Asp.net Core Webapi,我正在尝试在我的数据库中添加学生实体,如下所示: public class Student { public int ID { get; set; } public string Name { get; set; } public Course Course { get; set; } } public class Course { public int ID { get; set; } public string Name { get; set;
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public Course Course { get; set; }
}
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
课程类如下所示:
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public Course Course { get; set; }
}
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
}
课程表中的数据:
| ID | Course |
------------------------
| 1 | Math |
-----------------------
| 2 | Physics |
-----------------------
当我定义student时,如下所示:
var student = new Student
{
Name = "ABC",
Course = new Course { ID = 1, Name = "Math"}
};
试着把它加起来
context.Students.add(student);
await context.SaveChangesAsync()
未添加实体。我添加了这行代码
context.Entry(student).State = EntityState.Added;
但是没有任何变化。首先,您必须将外键CourseId设置为您的学生实体
Course existingCourse = GetCourseByIdFromDatabase();
Student student = new Student
{
CourseID = existingCourse.CourseID, //This ID comes from Db
Name = "ABC"
};
context.Students.Add(student);
await context.SaveChangesAsync();
学生实体
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public int CourseID { get; set; } //This is foreign key
public virtual Course Course { get; set; }
}
B课程实体:ICollection属性为您提供具有特定课程ID的所有学生
public class Course
{
public int CourseID { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
2如果您必须从数据库中引用现有课程,则必须从数据库中获取课程,并将courseId分配给学生实体
Course existingCourse = GetCourseByIdFromDatabase();
Student student = new Student
{
CourseID = existingCourse.CourseID, //This ID comes from Db
Name = "ABC"
};
context.Students.Add(student);
await context.SaveChangesAsync();
试试看,也许对你有帮助
编辑:
正如我对你上次评论的理解
如果你想让学生学习相应的课程
Course course = new Course
{
Name = "Math"
};
Course insertedCourse = context.Courses.Add(course);
Student student = new Student
{
CourseID = insertedCourse.CourseID,
Name = "ABC"
};
context.Students.Add(student);
await context.SaveChangesAsync();
你的get student方法看起来像
public Student GetStudent(int Id)
{
Student student = context.Students.Find(Id);
return new Student
{
StudentID = student.StudentID,
Name = student.Name,
Course = student.Course
};
}
您可以访问学生的课程,如
Student student = GetStudent(1);
string CourseName = student.Course.Name;
您可以根据需要使用async并等待上面的代码。您能告诉我,如何让学生实体也加载相应的课程吗?我使用了include方法,但我得到了一个错误。@A.M,如果您得到了student,那么它的虚拟课程属性将向您提供有关其指定课程的所有信息,只需在代码中执行,如Course.CourseID和Course。Name@A.M,如果有帮助,请查看答案的编辑部分,然后投票:请看这个问题:[链接]P.我的声誉不允许我投票:@A.M。,你试过在回答中使用编辑过的部分吗?我的工作项目中有所有代码。