1

我就在这行代码这个错误 -定义键此的EntityType

ReportRunnerEntities reportDB = new ReportRunnerEntities(); 

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

在DATABSE中的表定义了主键和设置标识。

我的模型 -

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; } 
    } 
} 

,这里是我的连接字符串 -

我怀疑它从来没有达到该数据库。正如我所说的,密钥在数据库中设置。

我错过了什么吗?

+0

请发布你正在得到的错误。 – Nix

+0

你在哪里说EF的ReportTypeId,ReportId和UserId是主键? –

回答

2

有一对夫妇的事情,我看应该改变:

  • ReportTypes应该REPORTTYPE

  • 公开名单的报告{获得; 集; }应公开 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代码优先作为您的堆栈,我会开始使用存储库和工作单元模式。这里是一个很好的帖子,如何设置:Entity Framework 4 CTP 4/CTP 5 Generic Repository Pattern and Unit Testable

+0

谢谢保罗,这非常有帮助。 – duckmike

相关问题