I am new to MS's MVC4, and I have been given a database for which I must build a CRUD front-end. The tables all have composite primary keys of the form [TableID, TableName, EffectiveDate]. I cannot alter the database design. I used the Database-first technique and the EF 5.x DbContext generator for C# tool to create the models, but the generated model files do not contain annotations for the composite keys. Here is an example of the Department table, with primary key = [DeptID, DeptName, EffDate].
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BillableUnits4.Models
{
using System;
using System.Collections.Generic;
public partial class Department
{
public int DeptID { get; set; }
public string DeptName { get; set; }
public System.DateTime EffDate { get; set; }
public string Status { get; set; }
public string Fund { get; set; }
public string DeptNo { get; set; }
public string RevenueAccount { get; set; }
public string BalanceSheetAccount { get; set; }
}
}
I'm betting the keys should look like this:
[key]
public int DeptID { get; set; }
[key]
public string DeptName { get; set; }
[key]
public System.DateTime EffDate { get; set; }
Do I even need to annotate the primary key components? If so, should I add the annotations to the generated model files? (regenerating the files would erase any changes I make by hand, obviously). Is there a way to tell MVC4 / Visual Studio to generate the files with the proper annotations?
You don't have to annotate something that is obvious for the database :) Your code will not use database specific annotations, so I wound't worry about that.
You might want to decorate your model with a [Required]
or other annotations that make sense for your app's data consistency. In such case you might either go with Partial Classes (http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx) or by implementing ViewModels
(that you could modify without worrying about the auto-generated classes that you shouldn't really modify)