I have an assembly generated using POCO template using Entity Framework (e.g. "Company.Models.dll").Besides generated POCOs I also have "follow up" partial classes that define meta data using System.ComponentModel.DataAnnotations. So for example Company.Models.Customer is auto-generated (in separate folder) and then I have partial class with same namespace. Within this partial class I define inner class for metadata...For example:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Company.Models
{
[MetadataType(typeof (CustomerMetaData))]
public partial class Customer
{
public override string ToString()
{
return String.Format("Id: {0}, Name: {1}", Id, Name);
}
//[Bind(Exclude = "Id")]
public class CustomerMetaData
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[DisplayName("Name")]
[Required(ErrorMessage = "Customer Name is required.")]
[StringLength(100, ErrorMessage = "Customer name cannot exceed 100 characters.", MinimumLength = 2)]
public string Name { get; set; }
}
}
}
The issue I am having is that I now want to use this assembly in my MVC project and want to use MVC specific attributes (like the commented out Bind attribute above).However, doing so requires making my Company.Models.dll dependent on System.Web.Mvc.dll.
I would like to avoid this at all costs if possible but how?
So far I am aware of 2 possible solutions and am asking community for their opinions or better approaches...
Solution 1
This solution has been discussed here: Using Data Annotations on POCO's with MVC for Remote Validation The "trick" was to use ViewModels and map (either mannually or using AutoMapper) POCOs to MVC project specific ViewModels. Then apply all necessary attributes to ViewModels instead of domain model POCOs. While this makes sense for large projects it is a bit overkill for small simple solutions...
Solution 2
Use Bind attribute in Controller action parameters (as seen on some http://www.asp.net/mvc tutorials). For example:
//
// POST: /Customer/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Customer customerToCreate)
{
if (!ModelState.IsValid)
return View();
// TODO: Add insert logic here
return RedirectToAction("Index");
}
Using this solution would allow to skip dependency on System.Web.Mvc from my POCO dll at the cost of having to remember to insert Bind attribute on all relevant Controller actions. Also, if I have multiple ASP.NET MVC projects the issue gets worse...
So, is there another way? ;)