MVC DB first Fix display Name
Asked Answered
F

2

14

I'm using mvc 4, with database first.

Everytime I refresh the model.edmx file, the display name attribute I added is removed. How can I the keep display name attribute between refreshes?

Fujio answered 26/9, 2012 at 21:0 Comment(0)
L
20

You are going to want to use System.ComponentModel.DataAnnotations. Here is a simplistic Example for a 'User' table in EF to show you how:

namespace YourNamespace.BlaBlaBla
{
    [MetadataType(typeof(UserHelper))]
    public partial class User { }

    public class UserHelper
    {
        [Display(Name = "Your New Title For Name")]
        public string Name { get; set; }
    }
}

You can also include validation in your class as well. Be sure it is a partial class named the exact same - also do not forget that it must be in the exact same namespace as your .edmx.

Lacasse answered 26/9, 2012 at 21:8 Comment(1)
Very helpful. Equipped with this, I wondered where I should place the extended partial classes. This answer turned out to be helpful for that: #30076161 The short answer: anywhere in the same project. I'm not sure if there is any further guidance on that, but I ended up creating an Extensions folder under the Models folder in my project. This keeps them out of the model itself so that they won't be overwritten, but in the same general area conceptually.Export
H
7

You need to use MetaDataTypes models..

[MetadataType(typeof(ModelMD))]
public partial class Model
{
//This is for "extending" the EF generated model, saying what class is used for metadata, in your case DisplayName
}

public partial class ModelMD
{

    [Display(Name = "Model_Title", ResourceType = typeof(DataFieldLabels))]
    public string Titulo { get; set; }

    [Display(Name = "Model_Description", ResourceType = typeof(DataFieldLabels))]
    public string Descripcion { get; set; }
}

In the above example I'm using Resource Files to get the Fields display names... but you could use it in a more harcoded way :)

You should create a new file in another folder, let's say "ModelMD". That way, once the models are regenerated this file is kept unchanged.

Important: The ModelMD file should use the same Namespace that the original model. If you put the file in a different folder it defaults to another namespace.

Historiated answered 26/9, 2012 at 21:8 Comment(3)
, ResourceType = typeof(DataFieldLabels) is not needed.Bertina
@mcfea, why not? It is the name of the resources where to find the "Name" property. If you want to hardcode the Display name, you don't need a Resource file, obviously.Historiated
well, perhaps you have a good reason there. I added my comment just as an indicator that it isn't needed as the display name shows in my UI without the additional information of ResourceType.Bertina

© 2022 - 2024 — McMap. All rights reserved.