Entity Framework Database First regeneration make

2020-06-06 01:29发布

问题:

I'm making a website with MVC .NET.

Since I'm an old school programmer who learn to design database first, I opted for the Database first approach. I'm also using "code generation" which create files with the extension .tt . Everything is working so far except one things that botters me.

Classic scenario:

  • I realise that I am missing one field
  • I add the field in the database.
  • I go into the edmx and choose to update the model from the database.

Then I go back to my code and things that use to work like special DisplayName tag that I put on top of model field were removed.

For example if I have this:

public partial class Blog
    {
        public Blog()
        {
            this.BlogComments = new HashSet<BlogComment>();
        }

        public int IDBlog { get; set; }
        public string Title { get; set; }

        [AllowHtml]
        public string Content { get; set; }
        public System.DateTime DateCreated { get; set; }
        public string Author { get; set; }

        public virtual ICollection<BlogComment> BlogComments { get; set; }
    }

It will become

public partial class Blog
    {
        public Blog()
        {
            this.BlogComments = new HashSet<BlogComment>();
        }

        public int IDBlog { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public System.DateTime DateCreated { get; set; }
        public string Author { get; set; }

        public virtual ICollection<BlogComment> BlogComments { get; set; }
    }

That is because the [AllowHtml] was added after a previous generation of the model. Is there a way to update the table and not remove all the tag that I add after the generation? How can I do that?

Right now, I manage this by doing some revert with SVN but it will soon be unmanagable.

Thanks

回答1:

Don't edit the generated files. Ever. Just. Don't. Do. It.

Instead, make your edits in partial files in a different directory. To add attributes, declare a Metadata class at the top of your partial class definition.

[MetadataType(typeof(BlogMetadata))]
public partial class Blog
{
    // it's possible to add logic and non-mapped properties here
}

Now in your Metadata class, you can define attributes or other logic:

public class BlahMetadata
{
    [AllowHtml] 
    public string Content{ get; set; } 
}


回答2:

No, there is no way to edit the generated code and not have it be replaced when you regenerate. That's why the code has warnings all over that says NOT TO EDIT IT.

You can, however, use partial classes to add additional functionality. If you don't know what a partial class is, then read about it here:

http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx

If you want to add attributes, then you have to use a special kind of partial class called a "buddy class".

http://hartzer.wordpress.com/2010/01/26/mvc-buddy-class/