定义此EntityType的键

时间:2011-03-06 01:15:52

标签: entity-framework-4 asp.net-mvc-3 entity-framework-ctp5

我在这行代码中得到了这个错误 -

    ReportRunnerEntities reportDB = new ReportRunnerEntities();

    public ActionResult Index()
    {
        **var types = reportDB.ReportTypes.ToList();**
        return View(types);
    }

数据库中的表定义了主键并设置了标识。

我的模特是 -

namespace ReportRunner.Models
{
    public partial class ReportRunnerEntities : DbContext
    {
        public DbSet<Reports> Report { get; set; }
        public DbSet<ReportTypes> ReportTypes { get; set; }
        public DbSet<Users> Users { get; set; }
    }
}

namespace ReportRunner.Models
{
    public partial class ReportTypes
    {
        public int ReportTypeId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Reports> Reports { get; set; }
    }
}

namespace ReportRunner.Models
{
    public class Reports
    {
        public int ReportId { get; set; } 
        public int ReportTypeId { get; set; }
        public int UserId { get; set; } 
        public string Title { get; set; }
        public ReportTypes ReportType { get; set; }
    }

}

namespace ReportRunner.Models
{
    public partial class Users
    {
        public int UserId { get; set; } //ArtistId
        public string Name { get; set; }
    }
}

这是我的连接字符串 -

       

我怀疑它永远不会到达数据库。正如我所说,密钥是在数据库中设置的。

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

我认为有些事情应该改变:

  • ReportTypes应为ReportType

  • 公开列表报告{get; 组;应该是公开的 ICollection Reports {get; 组; }

  • 如果你要定义一个 web.config中的连接字符串, 你需要告诉EF它是什么 使用你的构造函数 ReportRunnerEntities类如下:


    namespace ReportRunner.Models
    {
        public partial class ReportRunnerEntities : DbContext
        {
            public ReportRunnerEntities : base("name=NameOfConnectionInWebConfig")
            {}
            public DbSet<Reports> Report { get; set; }
            public DbSet<ReportTypes> ReportTypes { get; set; }
            public DbSet<Users> Users { get; set; }
        }
    }
    

您可以在此处详细了解:http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

请注意,如果您计划使用.NET MVC和EF Code First作为堆栈,我将开始使用Repository和Unit of Work模式。以下是关于如何进行设置的好帖子:Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable

相关问题