Reputation: 5684
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; }
Upvotes: 1
Views: 196
Reputation: 1632
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?
Upvotes: 0
Reputation: 11543
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:
Upvotes: 1