2017-10-18 114 views
0

我想知道为什么当首先使用代码时出现错误,而不是先数据库时出现错误。为了让您快速浏览一下我的应用程序,这是我的课:首次使用代码时出错

[Table("Votes")] 
public class Vote { 
    [Key()] 
    public int Id { get; set; } 

    [ForeignKey("User")] 
    public int UserId { get; set; } 
    public virtual User User { get; set; } 

    [ForeignKey("Answer")] 
    public int AnswerId { get; set; } 
    public virtual Answer Answer { get; set; } 
} 

而此行的代码之后:

Vote v = new Vote(); 
v.UserId = 1; 
v.AnswerId = 1; 

using (var context = new DatabaseContext()) { 
    context.Votes.Add(v); 
    context.SaveChanges(); 
} 

我得到错误:

An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll 

Additional information: An error occurred while updating the entries. See the inner exception for details. 

所以错误当我使用code firstSQLExpress数据库时发生。当我使用database firstSQLite数据库时,它就像一个魅力。相同的类,但没有错误。

我注意到,为避免出现错误,我必须初始化v.Userv.Answer。但为什么?在database first这是没有必要的。

+0

你可以尝试将它们设置为null并尝试? –

+0

@KeyurPATEL是的,它仍然不起作用。它仅在创建'User'和'Answer'的新实例并将它们分配给'v'对象属性时才起作用。 – Dawvawd

+0

请问您可以添加您的模型生成器 –

回答

0

看起来像你还没有编码db上下文类。您需要创建dbcontext类,例如。

using System.Data.Entity; 
using System.Data.Entity.ModelConfiguration.Conventions; 
using Votes.Models; 
namespace vote.Context 
{ 
    public class DatabaseContext : DbContext 
    { 
     public DatabaseContext() : base("VotesDatabase") 
     { } 
     public DbSet<Vote> Votes{ get; set; } 
     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
     } 
    } 
} 

下面是您了解基本codefirst MVC应用程序的示例。 Creating MVC Applications Using Entity Framework Code First Approach