Livy
Livy

Reputation: 663

How to specify a property as calculated in Entity Framework?

In examples from Microsoft, they implicitly defined a calculated property by providing only accessor without mutator:

public string NormalProperty { get; set; }
public string CalculatedProperty
{
    get { return "foobar" + NormalProperty; }
}

I also want to have a mutator in CalculatedProperty, which automatically trims the "foobar" suffix and assigns the result back into NormalProperty.

public string CalculatedProperty
{
    get { return "foobar" + NormalProperty; }
    set { NormalProperty = value.Substring(6); }
}

The issue is, Entity Framework now considers CalculatedProperty a normal property, and create a column named "CalculatedProperty" in the database.

I do not want to workaround with this by using functions. Can it be done through Attributes/Fluent API? I am using EF 6.1.

Upvotes: 1

Views: 383

Answers (1)

SWilko
SWilko

Reputation: 3612

It can be done in your DataContext in code first

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
   modelBuilder.Entity<Your_Class>().Ignore(x => x.CalculatedProperty); 
}

Upvotes: 1

Related Questions