1

I have an application (webservice), where numerous objects are inserted into a database or updated (with Entity Framework), but never read. So I even don't have read-access to this database.
Now a new requirement wants some properties to be inserted but never to be updated. I save all objects like this:

Type t = obj.GetType();
db.Set<TT>().AddOrUpdate(MapObject<TT>(obj)); //Maps to database entity and saves object

Now the question is, if there is an attribute I can tell a property to be inserted, but ignored while updating? In best case something like this:

[InsertOnly]
public string SomeText { get; set; }
Obl Tobl
  • 5,474
  • 7
  • 37
  • 62
  • There is no such attribute (feature) in EF. Also note that in order to detect the correct operation (`INSERT` or `UPDATE`), `AddOrUpdate` method *does read* from database, so *"I even don't have read-access to this database"* statement makes no sense. – Ivan Stoev Nov 06 '17 at 08:42

2 Answers2

1

In your unit of work save routine, check ChangeTracker and remove those records or properties that are marked as update. Something like this:

var modifiedItems = _dbContext.ChangeTracker.Entries()
    .Where(x => x.State == EntityState.Modified)
    .ToList();

EntityState has following types:

  • Detached
  • Unchanged
  • Added
  • Deleted
  • Modified
Afshar Mohebi
  • 9,219
  • 13
  • 76
  • 122
  • As far as I see in MSDN, `DbSet` has a method named `Add` for just adding. And there is not `AddOrUpdate` method: https://msdn.microsoft.com/en-us/library/system.data.entity.dbset(v=vs.113).aspx So calling just `Add` method is a safe way too. – Afshar Mohebi Nov 06 '17 at 07:20
  • `ChangeTracker` also can be used to find out state of properties too, if it can help. – Afshar Mohebi Nov 06 '17 at 07:25
  • This link may help: https://stackoverflow.com/questions/12661881/exclude-property-on-update-in-entity-framework – Afshar Mohebi Nov 06 '17 at 07:35
  • 1
    Thanks a lot! Learned something new and pointed me to the right direction! – Obl Tobl Nov 06 '17 at 11:00
0

You can add a custom attribute.

public class InsertOnly : Attribute
{}

If we consider

on your EF object, you add the custom property as such:

public class SomeEFClass {
       [InsertOnly]
       public int Id {get;set;}
   }

Then change

db.Set<TT>().AddOrUpdate(MapObject<TT>(obj)); //Maps to database entity and 

To include something like (This is pseudo code, don't expect it to run)

foreach(Property info pi in t.GetProperties())
{
    if(pi.GetCustomAttribute<InsertOnly>() == null)
    {
        //You can safely update this property
    }
    else
    {
        //This property is only for inserting
    }
}

I am uncertain if you can add the custom attribute via partial class overloading of a property? That might be worth a shot?

Morten Bork
  • 1,208
  • 9
  • 20