NOTE: V开发者_如何学编程S2010 / .NET 4, but without SP1 Beta at the moment, but if something in SP1 addresses this, it'd still be great to know about. :)
I have a particular database that I want to read from but will never write to. I don't see anything in the properties of the Model (looking in the EF designer) to mark it as read-only.
Certainly it looks like the simplest thing would be to add a partial class for the generated ObjectContext subclass (class FooModel : ObjectContext) to override SaveChanges(SaveOptions) and have it throw (maybe hooking up to SavingChanges and throwing would work too, I haven't actually tried either). That wouldn't disable change tracking, and AFAICT I'd have to loop through all the entity sets on context instance creation to mark them all as read-only (although that's a perf issue so not as critical as just making sure changes don't persist).
Certainly there's other options like having the connection string connect as a user that only has read access, but I wonder what options are available from an EF designer/model/instance perspective for having 'read-only' object contexts?
There are only few ways which make your model readonly
- Entity without primary key is read-only
- Entity mapped to DB view (without primary key) is read-only. Same applies if you use
DefiningQuery
in SSDL directly. - Entity mapped to
QueryView
in CSDL is read-only.QueryView
only works on top of other entities so this generaly doesn't solve your problem.
Your suggest with permissions to user accessing database looks like the most secure way. If you want to disallow saving changes overriding SaveChanges
and throwing something like NotSupportedException
also looks like a good solution.
Because you will work only with read-only entities you can also improve query performance by using MergeOptions.NoTracking
.
精彩评论