Search code examples
entity-frameworkmodel-view-controlleref-code-firstentity-framework-6code-first

Create a Class for extend Model Classes in EF code first


I have a model class that has for example 3 properties and corresponding table in my data base.

public partial class Person
{
    public string prop1 {set; get;}
    public string prop2 {set; get;}
    public string prop3 {set; get;}
}

Now I want derived property that for example create using prop1 and prop3 :

prop4 = prop1 + prop3;

I want to extend Person to have prop4. I create a partial class for Person to have prop4:

public partial class Person
{
     public string prop4 {set; get;}
}

but when I run the application I got this error:

Invalid column name 'prop4'

I change the above class like this:

public class PersonViewModel : Person
{
    public string prop4 { get; set; }
}

Invalid column name 'Discriminator'.\r\nInvalid column name 'Discriminator'.\r\nInvalid column name 'Discriminator'.\r\nInvalid column name 'prop4'

but if I create a class like this every think will be ok:

public class PersonViewModel
{
    public string prop1 {set; get;}
    public string prop2 {set; get;}
    public string prop3 {set; get;}
    public string prop4 {set; get;}
}

but using this solution I should rewrite all properties in ViewModel classes. Is there any other ways?

thanks


Solution

  • Use the NotMapped attribute or the fluent API Ignore method Ignoring a class property in Entity Framework 4.1 Code First