Entity Framework Code First - Can an existing table be mapped and made read only? - entity-framework

I need to use the users table from a parent site, is it possible to map the user table using the fluent API and have it be read only?

In case of EF code first you can't directly make it "read-only" but you can design your code to not expose DbContext and related DbSet outside of your DAL logic so rest of the application cannot add a new user.
In case of EDMX based mapping you can make it read only by mapping it as a custom SQL query (or database view) where insert, update and delete operations are not supported until you map them custom SQL commands or stored procedures.

According to a comment on ScottGu's blog, no.
Right now we don’t support read-only (or semi-read-only) properties in
Code First but this is an interesting suggestion that I will talk with
our design team about. In general the Entity Framework doesn’t have
support for marking something as “read-only” so we may have to wait
for another major .NET framework release to get this working. For now,
you will have to add business logic in your entity to allow the
property to be set only once.
Jeff Derstadt
Entity Framework Code First Team

Related

Getting familiar with Entity Framework when using existing database

We are currently rewriting an existing internal ASP.NET Web Forms application. Our application consists of a Web Api back end which uses Entity Framework 6 for data access and an front end which uses AngularJS.
We have an existing large database that I've created EF models using the Code-First Using Existing Database method and we are using data transfer object classes as inputs/outputs to our API methods so we aren't directly exposing our model classes. So basically, I'm trying to become proficient with EF, Web Api and AngularJS all at the same time. For the most part I'm fairly comfortable with the latter two, but for EF I haven't completely gotten comfortable with. I've watched a lot of the videos on Microsoft Virtual Academy but this is the first time I've had some hands-on experience with it.
We've been working on this application for a few months and so far we've only had to work with CRUD operations on our entities (POCO DTO's) which are flat objects with simple properties. However, we've finally come across some situations where we need to deal not only with our classes, but properties which are classes themselves; a parent-child relationship.
Therefore, I have the following questions:
I see that when we have a proper foreign key relationship in our DB, that virtual properties are created in EF, which from what I recall are to support lazy-loading. However, lazy-loading isn't really feasible in this environment where we are using web services (Web Api). Our object model does allow for some really large hierarchy of classes where a fully populated object and its children would mean a large amount of data would be passed around when that really isn't necessary, so in most cases a first level object is all we need. In some cases however, we do want to populate child classes, so my question is how do we do that, and where do we do that? I've looked at the automatically-generated code in the DB Context but we have also used scaffolded code to create our controllers. Which place do we need to do this? I've seen code samples showing how do to this but it hasn't said specifically where this code lies. It appears to be within a controller but I could be wrong.
If we do allow for 2- or more level hierarchy of objects, does EF automatically handle operations (updates, deletes, etc.) -- for example, if we have a "Company" object which has a collection of "Customer" objects, and we delete the "Company" object, do the related "Customer" objects get deleted too? Also, is a multi-step operation like that automatically performed within a transaction or do we need to explicitly set that up?
If I modify a model class or the DB context, seeing as this code is automatically-generated, that's generally bad practice as my changes could be overwritten, so I am assuming the controller code is where I want to make my changes. I am aware of database migrations but I have no experience with them and I am sure I'll need to use them at some point because I am fairly confident that our database may not have all the foreign key relationships necessary for EF to do everything we need at the moment.
I know this is a long post, but if anyone can give some guidance on how to do some of these things because it's not only me that's having to deal with this but I have two other developers on my team who are working on this project and we are all as inexperienced with this as the others are. Thanks
For the purpose of sending data across a web service, I'd suggest creating a DTO to hold the data you want to send and mapping your entities to the DTO instead of trying to send the entities themselves in your payload. It also protects your API from changes to your entity.
Cascading deletes are configurable, iirc, but I'm not 100% sure what the default is. Transactions are generally not implicit, so you will want to use those where you require them.
Not exactly sure what you are asking here. In general, how your entities/tables change depends on if you are using database-first or code-first. If you are using database-first (you will have a .edmx file in your solution that has the model matching your schema), you just update the SQL directly and update your entity model via the .edmx. If you use code-first, you will change the entities how you want them and run a database migration to update your database to match.
MSDN article about code-first migration: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Migrating from WCF Data Services to WebApiOdata

We are currently looking at migrating from WCF Data Services to WebApiOData. The problem that I see is that we have to create a method within a webApi controller for every single table/view that we have that we need to query from the client. The entity model is defined in an edmx with quite a few tables. Having one standard odata.svc that just allowed us to add a table to the edmx and just query it straight through the odata.svc was gold, having to add a method every time we add a view or table to the edmx will be a nightmare and if we are talking about > 50 tables/views it will just turn into a mess of methods everywhere.
Is there a simpler strategy for just having one controller that defines a global get method that we can just query on for all tables/views in the edmx? Or am I needing to create methods for everything?
RESTier is a layer of abstraction over Web API OData that should feel similar in ways to WCF Data Services, but still allow the flexibility of Web API OData. It already has an EF provider so ideally you should be up and running within minutes with a very small amount of code. Whether it works or doesn't work, we'd love to hear about your experience either in the comments on the GitHub pages or at odatafeedback#microsoft.com.

Logging changes through Entity Framework

Can anyone direct me to a good strategy for implementing change tracking in my Entity Framework model?
I have around 20 entities to track changes on (accessed via facades / unit of work) and I need to be able to display who changed what when on displaying the record in the UI.
I know there's Context.OnSavingChanges (or whatever it's called) but I'd probably want to access the changes in queries like context.MyEntity.ChangeLog
Must I create a ChangeLog entity, add associations to all the entities or is there a better via via savingchanges?
Richard
P.s. Have a great weekend!
Entity framework is ORM = API responsible for persistence and loading from database. What you persist or load is completely up to you so if you want change tracking you must to code it.
The most common approach is indeed using OnSavingChanges or overriding SaveChanges because you are usually saving changed executed by single user.
An old question but for anyone looking for auditing changes on EF >= 6 or EF Core, I worked on an open source library Audit.EntityFramework you could try.
See FrameLog, which is an open source library I wrote for this purpose. You call it from SaveChanges and it deals with the rest, including giving you a strongly-typed API for querying the logs.

MVC3 and EF Data first: what are the best practices?

It seems that most of the focus with MVC3 and EF4.1 is around "code first" - I can't seem to find any examples or tutorials that meet the following criteria:
uses an existing SQLServer database
has separate projects for web & data access (we will have multiple web apps sharing the same data access classes)
recommendations for validation
Does such an example or tutorial exist? Are there any documented "best practices" for how to accomplish this, or rationale for NOT having a solution structured this way?
It is quite common scenario and it depends if you want to use EDMX file for mapping or if you want to have mapping defined in code (like code first).
Both scenarios can be done as database first
You will create EDMX from existing database with build in EF tools in Visual Studio and you will use DbContext T4 generator template to get POCO classes and DbContext derived class
You will download EF Power Tools CTP and you will use its reverse engineering feature to generate code mapping, POCO classes and context for you
Neither of these approaches will add Data annotations. Data annotations on entities should not be used for client validation (that is bad practice) unless you are doing very simple applications. Usually your views have some more advanced expectations and validation in view can be different then on entity. For example insert view and update view can need different validations and it is not possible to perform it with single set of data annotation on the entity. Because of that you should move data annotations for validation to specialized view models and transform your entities to view models and vice versa (you can use AutoMapper to simplify this).
Anyway it is possible to add data annotations to generated classes via buddy classes but as mentioned it is not a good practice.

What's the best POCO status tracking strategy? (EF)

So I was reading about Entity Framework and based on my agile development scenario I decided to go with POCO objects.
But now I'm having some extra problems I don't know how to get away with.
I'm working with RIA services and Silverlight so when I'm going to Save an object of the server side I have to attach the object to an ObjectContext. The thing is that I must then change the ObjectState to Added or Modified.
So my question is what's the best approach to really know what state to change it to. I saw in Julia Lerman's book that she uses a State attribute in her POCO objects and she takes care managing that state on the client side before sending the object to the server. That state then is used to change the real EntitySate once attached.
I've also seen other samples where the Insert implementation checks on the Key of the Entity (object) to know whether it is new or not. For example, if ProjectId in my Project entity is 0 (zero) I know it has to be a new object.
To be honest I don't like any of those approaches because in both cases my developers have to do some extra-work to actually save the object.
I'd like the know pros and cons of both solutions and hopefully a new (better) solution I'm still not seing.
You can still have self tracking entities and poco. In visual studio if you search the community templates there is a self tracking poco template. this is what you want to use. If you can find the template look for your entities using Ientitywithobjecttracker.
http://msdn.microsoft.com/en-us/library/dd456848.aspx