Having some troubles with MetadataType, Annotations and EF
I am trying to use data annotations to validate my Entity Framework models using partial classes.
I was told in this article (MS开发者_如何转开发DN), that the partial class should be in the same namespace as the data model. My data model is located in EntityFrameworkDataProvider, so my partial class which is located in MyApp.Backend.Models looks like this:
using System.ComponentModel.DataAnnotations;
namespace EntityFrameworkDataProvider
{
[MetadataType(typeof(ItemMetaData))]
public partial class Item { }
public class ItemMetaData
{
[ScaffoldColumn(false)]
public object CreateDate { get; set; }
[Required]
public string DisplayName { get; set; }
[Required]
public string Description { get; set; }
}
}
I validate the model in my controller class like this:
[HttpPost]
public ViewResult Edit(Item item)
{
if (!TryUpdateModel(item))
{
return View(item);
}
return View("Details", item);
}
It compiles without errors. However, when trying to edit an item this error is what I get:
Compiler Error Message: CS0433: The type 'EntityFrameworkDataProvider.Item' exists in both 'long-path.DLL' and 'long-path.DLL'
I guess the Item class is being compiled twice or something. How should this error be prevented?
Your controller action is wrong. You should never use action parameters and TryUpdateModel
on the same type because it will insert the error messages twice in the model state. Your action should look like this instead:
[HttpPost]
public ViewResult Edit(Item item)
{
if (!ModelState.IsValid)
{
return View(item);
}
return View("Details", item);
}
As far as the compiler error message you are getting you haven't provided enough information so that I can help you. Make sure that this Item class is not defined in different locations and that it is indeed partial
in every single .cs
file you encounter it. I suspect that somewhere you have an Item
class defined which is not partial. What you should be aware of as well is that if this Item class is defined in a separate assembly, even if it is marked with partial, once compiled, the notion of partial no longer exists. Partial classes work only within the same assembly.
精彩评论