Putting DataAnnotation buddy class in another assembly

流过昼夜 提交于 2019-12-12 02:28:09

问题


I have a project called Model. All of my entities are in that project generated by EF Code first.

Public Partial Class Person
{
    ...
}

I don't want to touch my generated classes so I can create a partial class and add MetadataType attribute to it.

[MetadataType(typeof(Person_Metadata))]
public partial class Person
{
}

And here is my buddy class.

[Bind(Exclude="PersonID")]
public class Person_Metadata
{
    [Display(Name:="First name")]
    public string FirstName { get; set; }
    [Display(Name:="Last name")]
    public string LastName { get; set; }
}

The problem is, I want to move my buddy class to another assembly.

Model project has no reference to it so [MetadataType(typeof(Person_Metadata))] gives an error because it has no reference to Person_Metadata class.

I can use FluentValidation for validation part (and it works great), but what about other Metadata like: Display Attribute ?

I have also found this question: Adding DataAnnotation to class when using FluentValidation about managing MetaData with FluentValidation engine, but that looks like a long way to go and I prefer using data annotation attributes


回答1:


The problem is, I want to move my buddy class to another assembly.

That's impossible. Partial classes work only within the boundaries of the same assembly.

I can use FluentValidation for validation part (and it works great), but what about other Metadata like: Display Attribute ?

Nothing, they just could stay on your view model. Not on your domain model. Your view models are classes that you specifically design to meet the requirements of your views. It's on those view models that you would use the [DisplayFormat] and similar attributes.




回答2:


I know its too late to reply, but someone may get help from it.

I had similar situation where existing Model classes/Entities were created in an independent assembly and that was also in DotNet 3.5.

I Had to make reuse of the above assembly but this time in ASP.Net MVC 5. For that i figured out that the classes in Model assembly, if marked as public can be inherited in ASP.Net MVC project and there we can add buddy classes for data annotations.

It worked perfectly....



来源:https://stackoverflow.com/questions/17186379/putting-dataannotation-buddy-class-in-another-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!