For the EF Code First model entity, have a custom Setter on the property.

ef-code-first entity-framework

Question

Is it possible to override or add code to setter of property for entity model object in EF Code First approach.

e.g.

public class Contact
{
    [Key]
    public int Id { get; private set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string JobTitle
    {
        get;
        set { // eg. proper case the job title }
    }

}

I had tried having a public property marked NotMapped and this set/get to private/protected property that is. But it seems that the property has to public to be created in table.

1
13
1/24/2012 4:23:37 PM

Accepted Answer

You can write the logic in there if you want, just transform the property into a non-automatic one and perform the checks as you would do with a normal property.

 private string jobTitle;
 public string JobTitle
 {
      get { return jobTitle; }
      set
      {
           // do your fancy stuff or just jobTitle = value
      }
 }

Remember that if you change the value from db inside your setter it will probably be saved that way later on after you perform SaveChanges() on the context.

13
1/24/2012 7:19:48 PM

Popular Answer

Description

You can ignore the propertie using the ModelBuilder and .Ignore(...)

.Ignore(...) Excludes a property from the model so that it will not be mapped to the database.

Sample

public class MyDbContext : DbContext
{
    public DbSet<Contact> Contact { get; set; }
    // other DbSet's

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Contact>().Ignore(x => x.JobTitle);
    }
}

More Information



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow