Define the key for this EntityType
I get this error on this line of code -
ReportRunnerEntities reportDB = new ReportRunnerEntities();
public ActionResult Index()
{
**var types = reportDB.ReportTypes.ToList();**
return View(types);
}
The tables in开发者_运维技巧 the databse have primary keys defined and identities set.
My models are -
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; }
}
}
and here is my connection string -
I suspect that it's never reaching the database. As I said the keys are set in the database.
Am I missing something?
There are a couple things I see that should change:
ReportTypes should be ReportType
public List Reports { get; set; } should be public ICollection Reports { get; set; }
If you are defining a connection string in your web.config, you need to tell EF what one it is using the constructor in your ReportRunnerEntities class like this:
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; } } }
You can read more on that here : http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Just on a side note, if you are planning on using .NET MVC and EF Code First as your stack, I would start using the Repository and Unit of Work pattern. Here is a good post on how to set that up: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable
精彩评论