Is there any way to mark an entity as read-only and not specify any key for it?
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".