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

ef-code-first entity-framework

Question

Is it feasible to modify or add code to the entity model object's property setter using the 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 attempted to set/get to a private or protected property that is by having a public property designated as NotMapped. But it seems that in order to be formed in a table, the attribute must be made public.

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

Accepted Answer

If you'd like, you may add logic there; just change the property's status to non-automatic and carry out the checks as you normally would with a regular property.

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

Keep in mind that any changes you make to the value from the database inside of your setter will likely be stored in that manner.SaveChanges() on the surroundings.

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

Popular Answer

Description

The property may be disregarded by using theModelBuilder 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);
    }
}

Additional Details



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