[英]Entity Framework - seeding database - does PK need to be included in Seed method?
Following the MVC Music Store tutorial, the database is seeded with sample data. 在MVC音乐商店教程之后,数据库将附带样本数据。 The
Album
class is as follows: Album
类如下:
namespace MvcMusicStore.Models
{
public class Album
{
public int AlbumId { get; set;}
// ...
}
}
Then in the sample data class that's used in the tutorial, an Album
object is created like this within the Seed()
method: 然后在本教程中使用的示例数据类中,在
Seed()
方法中创建一个Album
对象:
new Album { Title = "The Best Of Billy Cobham",
Genre = genres.Single(g => g.Name == "Jazz"),
Price = 8.99M, Artist = artists.Single(a => a.Name == "Billy Cobham"),
AlbumArtUrl = "/Content/Images/placeholder.gif" }
In my project I have a class Tenant
: 在我的项目中,我有一个类
Tenant
:
public class Tenant
{
[key]
public int TenantId { get; set;}
// ...
}
In my Seed()
method, I create a Tenant like this: 在我的
Seed()
方法中,我创建了一个这样的租户:
new Tenant { UserId=1, UserName="Matthew" /*...*/ }
In my Seed()
method I've included the Tenant PK which is UserId - Tenant is derived from User. 在我的
Seed()
方法中,我包含了Tenant PK,即UserId - Tenant派生自User。 I'm wondering, because in the Seed() method I've explicitly said that the Tenant's PK of UserId is 1, will that cause a problem when the method run? 我想知道,因为在Seed()方法中我明确地说租户的UserId的PK是1,这会在方法运行时引起问题吗? I ask because in the music store tutorial, the author hasn't included an Album's PK.
我问,因为在音乐商店教程中,作者没有收录专辑的PK。
So the PK isn't explicitly stated when creating an Album. 所以在创建专辑时没有明确说明PK。 Will EF apply a PK by default?
EF默认会应用PK吗? I've just spent a while creating quite a lot of sample data for my own project, and I've put the PK for a lot of entities in manually - will EF accept this or will it cause me problems?
我花了一段时间为我自己的项目创建了大量的样本数据,并且我已经手动将很多实体放入PK中 - EF会接受这个还是会导致我出现问题? Is seeding the best way to generate sample data - alternatives?
播种是生成样本数据的最佳方式 - 替代方案?
When you don't add a [Key]
attribute, EF will try to find an int readable - writeable property named Id
or <yourClassName>Id
. 如果不添加
[Key]
属性,EF将尝试查找名为Id
或<yourClassName>Id
的int可读 - 可写属性。
That's all. 就这样。 And That's why AlbumId is taken as PK for class Album : No key attribute exists in that class, AlbumId =
<nameOfClass>Id
, it's a readable-writeable int. 这就是为什么AlbumId被作为类Album的PK的原因:该类中没有关键属性,AlbumId =
<nameOfClass>Id
,它是一个可读写的int。
If you have set a Key attribute, EF won't try to find another one. 如果您设置了Key属性,EF将不会尝试查找另一个属性。 It's just a convention, which allow you to be less verbose.
这只是一个惯例,让你不那么冗长。
For sample datas, Seed()
method's body is a fine way to put them in Code First. 对于样本数据,
Seed()
方法的主体是将它们放入Code First的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.