How do i use the AllowHtml attribute with the entity framework

China☆狼群 提交于 2020-06-29 02:21:34

问题


How would i go about adding the [AllowHtml] attribute to an entity framework generated class without the attribute being overwritten the next time the code is generated?

I am looking to simply allow CKEditor to post information back to my MVC4 application using Razor without having to use [ValidateReuqest(false)] on my Content entity class.


回答1:


You can use the [MetadataType] attribute to add metadata/attributes to your classes permanently without having to edit the original classes.

For the class Content create a new cs file in your project and replace the empty class with:

[MetadataType(typeof(ContentMetadata))]
public partial class Content
{

}

public class ContentMetadata
{
    [AllowHtml]
    public string ContentHtml { get; set; }
}

The partial class name must match the class name of the entity class exactly, and the attribute must match the definition of the attribute in the entity class exactly.

After a rebuild, this will now work as if you put the attribute within the entity class, but with the added bonus of not being overwritten every time.




回答2:


Add a new C# partial class file to the model folder with the same name as your entity class and apply the attribute there. Ensure that the namespaces for the partial classes match up, otherwise they are seen as different classes.

You can use the same partial class to set other attributes like [Display(Name="xxx")] for other properties.



来源:https://stackoverflow.com/questions/17964313/how-do-i-use-the-allowhtml-attribute-with-the-entity-framework

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