使用EF Fluent API创建2个主键

时间:2016-11-01 08:53:40

标签: c# entity-framework ef-fluent-api

我按照此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个主键:AlbumIdTitle。我只想要AlbumId作为我的主键。我做错了吗?

1 个答案:

答案 0 :(得分:0)

[Key]之上缺少

AlbumId注释。