Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Model from EDMX file - Add custom annotations to it, and make them stay?

Tags:

asp.net-mvc

How can I add annotations/attributes to my classes or methods of classes in my model, generated from my Model.edmx file? The reason I'm asking this is because every time I add an annotation to a class Model.Designer.cs, this annotation disappears when I make changes to my Model.edmx file through the designer.

More specifically, I am looking for a way to add the AllowHtml annotation to a specific property within one of my model classes, and make it stay there even after messing around with it in the model designer view.

Here's the controller code. The Content property of the Segment class is the one causing my controller to crash when being populated with HTML.

    [FacebookAuthorize(Permissions = AuthenticationController.ExtendedPermissions, LoginUrl = "/Authentication/LogOn?ReturnUrl=~/Segment/Contribute")]
    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Contribute(int id, string content)
    {

        var container = new ModelContainer();

        var parent = container.SegmentSet.SingleOrDefault(s => s.Id == id);

        var segment = new Segment();
        segment.Content = content; //this crashes with HTML data.
        segment.Owner = AuthenticationController.Authentication.GetUser(container);
        segment.TimeModified = DateTime.UtcNow;
        segment.TimePosted = DateTime.UtcNow;

        container.AddToSegmentSet(segment);

        if (!parent.Children.Contains(segment))
        {
            parent.Children.Add(segment);
            segment.Parent = parent;
        }

        container.SaveChanges();

        return RedirectToAction("Index", "Home");
    }
like image 831
Mathias Lykkegaard Lorenzen Avatar asked Dec 31 '11 17:12

Mathias Lykkegaard Lorenzen


1 Answers

You can use MetadataTypeAttribute to extend your classes:

[MetadataType(typeof(MyEdmxClassExtension))]
public partial class MyEdmxClass { }

public class MyEdmxClassExension
{
    [AllowHtml] // Add the attributes you want to find on your property
    public string ThePropertyYouWantToExtend { get; set; }
}

This code goes in a separate file than the one generated or you will lose it, too, of course.

Edit

In response to the comments below, I believe you have two questions. Your original question is answered using the MetadataTypeAttribute and, for the second, you should probably open another question.

like image 152
Jim D'Angelo Avatar answered Oct 26 '22 22:10

Jim D'Angelo