0

Suppose I have a database table User with a 1:1 relationship with table Role. The class generated by Entity Framework would be:

// Generated by Entity Framework
public partial class User
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Guid RoleID { get; set; }
    public Role Role { get; set; }
}

Now for auditing purposes I want to save the Role name, so I define my own partial class with my own property:

// Written by myself
public partial class User
{
    public string RoleName {get { Role.Name; }}
} 

How would I tell EntityFramework to track User.RoleName just like it tracks User.Name?

var modifiedEntities = ChangeTracker.Entries();
foreach (var change in modifiedEntities)
{
    var name = change.Property("Name").OriginalValue; // ok
    var roleName = change.Property("RoleName").OriginalValue; // gives error
}

The error says "Member 'OriginalValue' cannot be called for property 'RoleName' on entity of type 'User' because the property is not part of the Entity Data Model."

user1447435
  • 145
  • 1
  • 10
  • I guess I am not getting why you need to store the RoleName, should not it already be in your Role Table? And, your User table has RoleID as the foreign key stored in it? It would be a bad practice to store again the RoleName in your User table though.. – Ashraf Iqbal Mar 06 '16 at 01:08
  • This is for auditing purposes. The role name might change in the future so I want to persist the value at the time it was allocated to the user. – user1447435 Mar 06 '16 at 08:24
  • Did you tried adding a `set` to the `RoleName` property? – thepirat000 Sep 08 '16 at 14:34

0 Answers0