无效的对象名称'dbo.UserNotes'。异常 - ASP.NET MVC 4

时间:2013-10-24 11:50:49

标签: c# asp.net asp.net-mvc entity-framework

看来EF不会创建这一个表

NotesModels.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;

namespace note.DO.Models
{
public class NotesContext : DbContext
{
    public NotesContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserNotes> Notes { get; set; }
    public DbSet<UserProfile> UserProfiles { get; set; }
}

[Table("UserNotes")]
public class UserNotes
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int NoteId { get; set; }

    public virtual int UserId { get; set; }

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

    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime? Added { get; set; }
    public DateTime? Edited { get; set; }  
}

public class CreateNoteModel
{
    [Display(Name = "Author")]
    public UserProfile Author { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Title")]
    public string Title { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    [Display(Name = "Content")]
    public string Content { get; set; }

    [DataType(DataType.DateTime)]
    [Display(Name = "Added on")]
    public DateTime? AddedOn { get; set; }
}
}

我使用这些类生成了控制器。但是,当我尝试添加注释时,我会遇到以下异常:

  

无效的对象名称'dbo.UserNotes'。

......由此行触发:

db.SaveChanges();

我尝试过的事情:

  • 将架构更改为“dbo”(通过添加[Table(“UserNotes”,Schema:“dbo”)])))
  • 从Visual Studio手动删除整个数据库文件
  • 将plurar表单更改为单数和后退
  • 重新安装实体框架

有什么想法吗?也许我正在做一些非常愚蠢而没有注意到的事情?

编辑:UserProfile类和数据上下文:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

(...)

(other models)

1 个答案:

答案 0 :(得分:1)

在阅读Gert Arnold的评论后,我做了这个

将此行添加到UsersContext:

public DbSet<UserNotes> Notes { get; set; }

所以这就是它现在的样子:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Notes> Notes { get; set; }
}

它完美无瑕!现在正在创建表,我可以毫无问题地添加条目。