Following the MVC Music Store tutorial, the database is seeded with sample data. The Album
class is as follows:
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:
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
:
public class Tenant
{
[key]
public int TenantId { get; set;}
// ...
}
In my Seed()
method, I create a Tenant like this:
new Tenant { UserId=1, UserName="Matthew" /*...*/ }
In my Seed()
method I've included the Tenant PK which is UserId - Tenant is derived from 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? I ask because in the music store tutorial, the author hasn't included an Album's PK.
So the PK isn't explicitly stated when creating an Album. Will EF apply a PK by default? 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? 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
.
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.
If you have set a Key attribute, EF won't try to find another one. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.