【发布时间】:2017-02-05 13:21:00
【问题描述】:
当我尝试使用 Entity Framework 向我的学生添加书籍时,它会抛出异常“违反多重性约束。关系‘LibarySystem.DataModel.Student_LendedBooks’的角色‘Student_LendedBooks_Source’的多重性为 1 或 0..1”。我该如何解决?我对实体框架不是很熟悉。感谢您的帮助。
DbContext 类:
public class DbContext : System.Data.Entity.DbContext {
public DbSet<Student> Students { get; set; }
public DbSet<Book> Books { get; set; }
}
学生班级:
public class Student {
public Student() {
LendedBooks = new HashSet<Book>();
}
[Key]
public string PESEL { get; set; }
public string Name { get; set; }
public string SecondName { get; set; }
public string Surname { get; set; }
public string Class { get; set; }
public virtual ICollection<Book> LendedBooks { get; set; }
}
书籍类:
public class Book {
public Book() {
IsLend = false;
}
[Key]
public string CatalogueNumber { get; set; }
public string StudentPesel { get; set; }
public virtual Student Student { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public DateTime? DateOfLend { get; set; }
public DateTime? DateOfReturn { get; set; }
public bool IsLend { get; set; }
}
和添加方法:
public static void AddBookToStudent(Student student, Book book) {
using (var context = new DbContext()) {
var findStudent = context.Students.Find(student.PESEL);
var findBook = context.Books.Find(book.CatalogueNumber);
if (findBook != null) {
findBook.DateOfLend = DateTime.Today;
findBook.DateOfReturn = book.DateOfLend + new TimeSpan(7, 0, 0, 0);
findBook.StudentPesel = findStudent?.PESEL;
findBook.Student = findStudent;
findBook.IsLend = true;
}
findStudent?.LendedBooks.Add(book);
context.SaveChanges();
}
}
【问题讨论】:
-
您是否尝试将相同的
Book添加到多个Student?
标签: c# .net entity-framework