我有以下实体:
public class Book {
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int? AddedByUserId { get; set; }
public virtual ICollection<Author> Authors { get; set; } = new HashSet<Author>();
}
public class Author {
public int Id { get; set; }
public int BookId { get; set; }
public string Name { get; set; } = string.Empty;
public int? AddedByUserId { get; set; }
public Book Book { get; set; } = new Book();
}
我尝试添加Author
并将BookId
设置为现有值。
var newAuthor = new Author();
newAuthor.BookId = 1;
_dbContext.Authors.Add(author);
当我检查ChangeTracker
,看看DbContext要做什么:
var longView = _dbContext.ChangeTracker.DebugView.LongView;
表示添加Author
、Book
、User
。
Author {Id: -2147482646} **Added**
Id: -2147482646 PK Temporary
AddedByUserId: 1
DateAdded: '11/25/2022 8:22:11 PM'
Name: 'My Author Name'
BookId: -2147482643 FK Temporary
Book: {Id: -2147482643}
Book {Id: -2147482643} **Added**
Id: -2147482643 PK Temporary
AddedByUserId: -2147482645 FK Temporary
DateAdded: '1/1/0001 12:00:00 AM'
Name: ''
AddedByUserId: {Id: -2147482645}
User {Id: -2147482645} **Added**
Id: -2147482645 PK Temporary
DateAdded: '1/1/0001 12:00:00 AM'
Name: <null>
RowVersion: <null>
当设置BookId
外键时,如何才能只添加新的Author
?我应该设置对象而不是id吗?
newAuthor.Book = _dbContext.Book.Find(1);
newAuthor.Book
不是空的,EF不会跟踪它,所以它会把它当作一本新书。有多个选项:
- "Clear"图书对象:
var newAuthor = new Author();
newAuthor.BookId = 1;
newAuthor.Book = null;
- 附加图书:
var newAuthor = new Author();
newAuthor.Book.Id = 1;
_dbContext.Books.Attach(newAuthor.Book);
_dbContext.Authors.Add(author);
- 从数据库中获取图书(如您自己所建议的)
是的,不要直接修改外键,而是让ef core通过设置对象本身来完成它的工作。也不要引用new()
导航属性:
public Book Book { get; set; } = new Book();
为集合导航属性这样做是很好的,因为它可以避免在尝试添加到集合时出现null异常,例如