Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attributes to a derived type

I am working with entity-framework. I have a partial class called Company that is generated by EF. The partial class looks like:

The type 'BaseModels.Company' already contains a definition for 'CompanyName'"

public partial class Company {
    public string CompanyId { get; set; }
    public string CompanyName { get; set; }
}

What I want to do is create a derived class from Company that has an extra property.

public class MyCompany : Company {
    public string UploadName { get; set; }
}

But I want to decorate the base type property CompanyName with a custom attribute.

I went to the following location: How do I add an attribute to the field of the base class from child class?

Which does answer my question. The problem is if I marked the CompanyName property in the base class as "virtual", then EF could regenerate the code which would override my stuff.

I tried to define a partial class, but VS 2013 complained when I tried to add:

public partial class Company {
    [Renderer("html")]
    public virtual string CompanyName { get; set; }
}

by stating that the property name already existed.

How would I get around this hurdle?

like image 970
coson Avatar asked Nov 09 '22 05:11

coson


1 Answers

You cannot with partial class define property that already exists. You add attribute over existing property you need to use MetadataTypeAttribute. Create partial class:

[MetadataType(typeof(CompanyMetadata))]
public partial class Company { }

and add metadata class to your project with your property with desired attribute:

public class CompanyMetadata
{
    [Renderer("html")]
    public string CompanyName { get; set; }
}
like image 193
mr100 Avatar answered Nov 14 '22 22:11

mr100