[英]When we Seed a database in ASP.NET MVC, why do we use a lamba expression for returning the id of elements?
In all the examples I see, such as 在我看到的所有示例中,例如
protected override void Seed(BookService.Models.BookServiceContext context)
{
context.Authors.AddOrUpdate(x => x.Id,
new Author() { Id = 1, Name = "Jane Austen" },
new Author() { Id = 2, Name = "Charles Dickens" },
new Author() { Id = 3, Name = "Miguel de Cervantes" }
);
context.Books.AddOrUpdate(x => x.Id,
new Book() { Id = 1, Title = "Pride and Prejudice", Year = 1813, AuthorId = 1,
Price = 9.99M, Genre = "Comedy of manners" },
new Book() { Id = 2, Title = "Northanger Abbey", Year = 1817, AuthorId = 1,
Price = 12.95M, Genre = "Gothic parody" },
new Book() { Id = 3, Title = "David Copperfield", Year = 1850, AuthorId = 2,
Price = 15, Genre = "Bildungsroman" },
new Book() { Id = 4, Title = "Don Quixote", Year = 1617, AuthorId = 3,
Price = 8.95M, Genre = "Picaresque" }
);
}
from here , I see that there is a lamba expression as the first parameter of the AddOrUpdate
and it's always shown as the Id
(primary key?) of the table. 从这里 ,我看到有一个兰巴表达式作为第一个参数AddOrUpdate
它总是显示为Id
(主键?)的表。 Can someone explain what that lamba expression is for? 有人可以解释一下该兰巴表达的目的吗? Is it for checking whether the Id
is null
? 是否用于检查Id
是否为null
? I'm confused. 我糊涂了。
It's to define which property should be checked to see if the Seed()
-method should UPDATE
or INSERT
. 它定义了应该检查哪个属性,以查看Seed()
方法是否应该UPDATE
或INSERT
。 In this case, if the given ID is already in the database, it will not insert it again (but update the existing entry). 在这种情况下,如果给定的ID已存在于数据库中,则不会再次插入它(而是更新现有条目)。
But you could also check on Title
, Year
, ... or other properties to define if the entry should be inserted or updated in your database. 但是,您也可以检查Title
, Year
,...或其他属性,以定义是否应在数据库中插入或更新条目。 Basically it's to prevent duplicates in your database, but you can give meaning to what a duplicate is to you. 基本上是为了防止数据库中出现重复项,但是您可以赋予重复项含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.