我按照此https://mva.microsoft.com/en-us/training-courses/implementing-entity-framework-with-mvc-8931?l=mBKHDFC3_9204984382的教程进行操作。这是我的代码
namespace FluentAPI
{
class Program
{
static void Main(string[] args)
{
using (var context = new MusicContext())
{
var album = new Album() { Price = 9.95m, Title = "YUhuu" };
context.Albums.Add(album);
context.SaveChanges();
}
}
public class Album
{
public int AlbumId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
public class MusicContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MusicStore");
modelBuilder.Entity<Album>().HasKey(t => t.AlbumId);
//tell EF to map string into varchar
modelBuilder.Entity<Album>().Property(t => t.Title).IsUnicode(false);
//Album id not going to be identity
modelBuilder.Entity<Album>()
.Property(t => t.AlbumId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
base.OnModelCreating(modelBuilder);
}
public DbSet<Album> Albums { get; set; }
}
}
}
它假设在数据库中创建一个表,AlbumId
作为主键。但是当我运行这个程序时,表结果不是我所期望的。有2个主键:AlbumId
和Title
。我只想要AlbumId
作为我的主键。我做错了吗?
答案 0 :(得分:0)
[Key]
之上缺少 AlbumId
注释。