Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Default behavior for entity framework method mapping

My entity classes need to also comprise logic.

What will entity framework code-first mapper do, when an entity with a method is encountered?

Will it just ignore and map only properties to a database?

Side question: Is it a good practice to have a logic in an entity classes at all?

Upvotes: 0

Views: 179

Answers (2)

Eranga
Eranga

Reputation: 32437

Methods in your entities will be ignored when EF performs the model discovery. You can even add extra properties and mark them as not mapped.

public class Foo
{
     public int Id { get; set; } 

     public Bar Bar { get; set; }

     public string Baz { get; set; }

     public ValidationResult Validate(ValidationContext context)
     {
     }
}

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<Foo>().Ignore(f => f.Baz);

         modelBuilder.Ignore<Bar>();
    }
}

Here Bar, ValidationResult, ValidationContext will not be part of the model and Baz property will not be mapped to a column.

Its perfectly OK to have logic in your entity classes.

Upvotes: 1

undefined
undefined

Reputation: 34238

It will just ignore methods completely it only looks at properties. IMO you shouldnt ever have logic in entity classes. If you want to attach logic to entites do it in extention methods

Upvotes: 0

Related Questions