我是entityframework的新手,我从这段代码开始,但我不知道为什么我有一个异常处理程序" System.Data.Entity.ModelConfiguration.ModelValidationException'发生在EntityFramework.dll" in line var count = context.Albums.Count();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace entityframework1
{
class Program
{
static void Main(string[] args)
{
using (var context = new MusicAlbumContext())
{
var count = context.Albums.Count();
Console.WriteLine(count);
context.Albums.Add(new Album() { Name = "best", Cost = 34.43m });
context.SaveChanges();
Console.WriteLine(count);
Console.Read();
}
}
}
public class MusicAlbumContext:DbContext
{
public DbSet<Album> Albums { get; set; }
}
public class Album
{
public string Name { get; set; }
public decimal Cost { get; set; }
}
}
答案 0 :(得分:0)
您需要执行以下过程
class Program
{
static void Main(string[] args)
{
using (var context = new MusicAlbumContext())
{
var count = context.Albums.Count();
Console.WriteLine(count);
context.Albums.Add(new Album() { Name = "best", Cost = 34.43m });
context.SaveChanges();
Console.WriteLine(count);
Console.Read();
}
}
}
public class MusicAlbumContext:DbContext
{
public MusicAlbumContext()
: base("connectionstring")
{
}
static MusicAlbumContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MusicAlbumContext>());
}
public DbSet<Album> Albums { get; set; }
}
public class Album
{
public string Name { get; set; }
public decimal Cost { get; set; }
}
之后运行以下commnads enable-migrations contextname add-migration InitialCreate update-database -verbose -fource