[英]How to assign entity Id to another entity without inserting first entity into database in Entity Framework, C#?
Suppose I have 2 tables with many to one relationship: Book -> Author. 假设我有2个具有多对一关系的表:书籍->作者。 Author can have multiple books.
作者可以有多本书。 So, Book entity has Author and AuthorId navigation properties.
因此,Book实体具有Author和AuthorId导航属性。
For example Author table contains one row: AuthorName. 例如,作者表包含一行:AuthorName。 I want to insert new Author only if the name is unique.
我只想在名称唯一的情况下插入新作者。
So, what I do: 所以,我该怎么做:
var book = new Book();
var authorFromDatabase = getAuthorFromDbByName("author name");
if(authorFromDatabase == null)
{
// insert new author if it is not already in the database
book.Author = new Author("author name");
}
else
{
// how to assign AuthorId to book so that it will not add new Author to the db??
// the following line inserts new author into the db
book.AuthorId = authorFromDatabase .AuthorId;
}
So, how can I assign AuthorId to book and not insert a new Author into the db if it's already there? 因此,如何将AuthorId分配给book,并且如果新的Author已经存在,则不将其插入数据库?
Setting the .AuthorId
property would not create a new Author
in the DB - how could it? 设置
.AuthorId
属性不会创建一个新的Author
在DB -怎么可能呢? You're not actually constructing a new Author
object and adding it to your DbContext
. 您实际上并不是在构造新的
Author
对象并将其添加到DbContext
。 From what you've given us to look at, it would seem if(authorFromDatabase == null)
always resolves as True
. 从您给我们的看,似乎
if(authorFromDatabase == null)
始终解析为True
。 Have you debugged the code to ensure that the else
block is ever executed? 您是否调试了代码以确保
else
块曾经执行过?
You should probably show more of of your code, such as your Author
and Book
entity classes as well as your getAuthorFromDbByName(...)
method implementation and where you instantiate your DbContext
instances. 您可能应该显示更多代码,例如
Author
和Book
实体类以及getAuthorFromDbByName(...)
方法实现以及在何处实例化DbContext
实例。
If it is about uniqueness I would do something like this: 如果是关于唯一性,我会做这样的事情:
// some code
newBook.Author = CreateOrGetAuthor("The Name");
// more code
private Author CreateOrGetAuthor(string authorName)
{
var author = _context.Authors.SingleOrDefault(a => a.Name.Equals(authorName, StringComparison.CurrentCultureIgnoreCase));
if (author == null)
{
author = new Author();
author.Name = authorName;
}
return author;
}
Now it depends on if you're using transactions around those both calls. 现在,这取决于您是否正在使用这两个调用周围的事务。 If not, you have to call _context.SaveChanges() first and the return the author in CreateOrGetAuthor.
如果不是,则必须首先调用_context.SaveChanges()并在CreateOrGetAuthor中返回作者。 Otherwise it won't have an ID.
否则它将没有ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.