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.
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.
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.
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);
}
}