Is there any way to mark an entity as read-only and not specify any key for it?
-
Code First and read only are kind of mutually exclusive. Just out of curiosity why would you not want a primary key?Brian– Brian2012-02-23 15:01:03 +00:00Commented Feb 23, 2012 at 15:01
-
2Enttity is mapped to a view and I don't want update/insert on it, an have no key on it either.Otake– Otake2012-02-23 15:32:42 +00:00Commented Feb 23, 2012 at 15:32
-
EF will not do updates on views by default.Gert Arnold– Gert Arnold2012-02-23 16:00:45 +00:00Commented Feb 23, 2012 at 16:00
-
@GertArnold, that is incorrect. You can update/insert views in EF.Otake– Otake2012-02-23 16:29:25 +00:00Commented Feb 23, 2012 at 16:29
-
Is this information outdated then? Could be, EF develops pretty fast.Gert Arnold– Gert Arnold2012-02-23 16:38:06 +00:00Commented Feb 23, 2012 at 16:38
4 Answers
There are a couple of things that you can do to enforce read-only in Code First. The first is to use AsNoTracking() when you query.
var readOnlyPeople = (from p in context.People
where p.LastName == "Smith"
select p).AsNoTracking();
This tells Code First to not track changes to these entities, so when you call SaveChanges() no changes made to these objects will be persisted.
The seccond thing you can do is set the state to Unchanged before calling SaveChanges().
context.Entry(person).State = EntityState.Unchanged;
context.SaveChanges();
This tells Code First to ignore any changes that have been made to that entity.
As far as not having a key, all entities must have a key. This may not necessarily map to a primary key in the database, but it "must uniquely identify an entity type instance within an entity set".
3 Comments
Using code-first in EF6, I created some entities that reflect Views, which obviously shouldn't be modified or saved. To prevent the Entity from being changed, I used protected set properties:
public class TransplantCenterView
{
public string TransplantsThisYear { get; protected set; }
}
Entity Framework is still able to set this property, but other developers can't accidentally do it without a compile-time error. This works great, but it seems the better solution would be to eliminate tracking completely.
Thanks to reggaeguitar's answer, it appears there is an answer to this (please also vote his answer up if the following is helpful), which has allowed me to change my code from:
public class MyContext : DbContext
{
public DbSet<TransplantCenterView> TransplantCenterViews { get; set; }
}
To:
public class MyContext : DbContext
{
// appears the DbSet is still needed to make Set<Entity>() work
protected DbSet<TransplantCenterView> _transplantCenterViews { get; set; }
// this .AsNoTracking() disables tracking for our DbSet.
public DbQuery<TransplantCenterView> TransplantCenterViews
{
get { return Set<TransplantCenterView>().AsNoTracking(); }
}
}
I don't know of any pros and cons to this, but my existing code has continued working without any hitches, so seems a win.
2 Comments
protected set solution.If you want the entire entity to be read-only you can do this
/// Using a dbquery since this is readonly.
/// </summary>
public DbQuery<State> States
{
get
{
// Don't track changes to query results
return Set<State>().AsNoTracking();
}
}
source http://www.adamtuliper.com/2012/12/read-only-entities-in-entity-framework.html
6 Comments
MyEntityName is not part of the model for the current context." So, added protected DbSet<MyEntityName> _hiddenMyEntitiesName {get; set;} and then things worked. It would be worthwhile to add the DbSet<> into your code above so people don't run into the same confusion...or if there's another way? But thanks for putting me on the right path.You can also make it read-only as a more "global" rule for a specific entity by type. Simply override the appropriate SaveChanges* method and set the entity's state if you see that EF is trying to add it during the save.
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
foreach (var entry in ChangeTracker.Entries())
{
if (entry.Entity.GetType() == typeof(<YOUR_TYPE_HERE>) && entry.State == EntityState.Added)
{
entry.State = EntityState.Detached;
}
}
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}