1

I have couple of entity who inherits base class with common fields like below:

[DataType(DataType.Text)]
[StringLength(100)]
public string CreatedBy { get; set; }

[DataType(DataType.DateTime)]
public DateTime? CreatedDate { get; set; }

[DataType(DataType.Text)]
[StringLength(100)]
public string ModifiedBy { get; set; }

[DataType(DataType.DateTime)]
public DateTime? ModifiedDate { get; set; }

I would like to fill these fields right before it goes to contex. Is there some events/method/handler which I may reuse to do some actions with entity before it placed to context? I would like these fields are filled at the time its added to context, not put to the database.

Solution: Entity Framework/SQL2008 - How to Automatically Update LastModified fields for Entities?

Community
  • 1
  • 1
Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
  • possible duplicate of [Extend base type and automatically update audit information on Entity](http://stackoverflow.com/questions/2588544/extend-base-type-and-automatically-update-audit-information-on-entity) – Gert Arnold Dec 25 '12 at 09:19
  • Yeah the answer there is to use setter methods within default constructor. Basically the same as I suggested. – Mukus Dec 25 '12 at 09:50

1 Answers1

0

Not sure 100% what you mean by filling these fields to context before they go to the database.. but if you want to persist them at some point these fields should be part of an object (entity) and then you can populate the poco using the setter method. You can always call context.Save()/Update() methods when you want to.

Mukus
  • 4,870
  • 2
  • 43
  • 56
  • For example, I creating an entity. This entity (among many others) inherits base class with specified fields. So I do not want to fill these properties manually for each entity. I prefer to place filling logic (for these 4 properties) in handler in ancestor of DbContext to fill it transparently and do not think about it anymore. – Alex G.P. Dec 25 '12 at 07:33
  • Use the base class's constructor and set these values to a default value. – Mukus Dec 25 '12 at 08:49
  • Here's similar posts that may help you - http://stackoverflow.com/questions/3137738/how-to-set-default-value-for-pocos-in-ef-cf (look at the second and third answers) http://stackoverflow.com/questions/10135058/ef-4-3-code-first-how-to-set-default-value (look at the accepted answer) – Mukus Dec 25 '12 at 08:50
  • That is not what I want. I do not need to setup default values. – Alex G.P. Dec 25 '12 at 09:20
  • 1
    I think what you are looking for is to have the dates populated automatically just before they are saved. I think this is what you are looking for http://stackoverflow.com/questions/3879011/entity-framework-sql2008-how-to-automatically-update-lastmodified-fields-for-e – Mukus Dec 25 '12 at 09:55