Does anyone know if it's possible to not use the navigation properties feature of the entity framework for tables linked with a foreign key?
for example, if my client table has an AddressId, I want that AddressId in my model, I don't want it to have a .Address property. But I have thus far been unable to figure out how to do this.
Sure, you can do this. It's just that the designer won't help you very much. Delete the navigation property, and add a scalar property for AddressId. It will work, but you'll have to be careful about hitting Update Model in the designer, as it may try to "fix" things for you. It's worth getting used to editing EDMX; it's not that bad.
In the designer, you can set the navigation properties as having Private getters/setters. While they will still be there, because Entity Framework (by default) does lazy loading, it won't actually retrieve any data from the database at runtime. And they won't respawn the next time you update the model from the database.
Related
I'm migrating from Linq-to-SQL to Entity Framework (4.4), using Database First with a DbContext. I'm wondering whether the following behavior is normal:
using (var e = new AgendaEntities()) {
var store = e.Stores.First();
var office = e.Offices.Create();
office.Store = store; // Set association
Console.WriteLine(office.StoreID); // shows Guid.Empty, expected store.ID!
}
In L2S, setting the Store association to an entity would also update the StoreID key. In EF, this doesn't seem to be happening. This is regardless of whether the entities are new or loaded from the context.
When I SaveChanges, it saves correctly and the StoreID is updated to match office.ID, but why does this only happen after the save?
Is there something I'm missing, or am I now supposed to keep foreign keys in sync manually?
Solution Edit:
This is called property fixup, and used to be done automatically by the generated proxies. However, with DbContext this is no longer the case. According to this Connect issue, this is by design.
Hello,
The DbContext template actually doesn't generate classes that will be used as change tracking proxies - just lazy loading proxies (which don't do fix-up). We made this decision because change tracking proxies are complex and have a lot of nuances that can be very confusing to developers.
If you want fix-up to occur before SaveChanges you can call myContext.ChangeTracker.DetectChanges.
~EF Team
An alternative is to call DbContext.Entry(entity), which will sync up the entity. This is described in this article: Relationships and Navigation Properties under "Synchronizing the changes between the FKs and Navigation properties"
No. Entity framework does this for you. Read Relationships and Navigation Properties for more information.
By assigning a new object to a navigation property. The following
code creates a relationship between a course and a department.
If the objects are attached to the context, the course is also
added to the department.Courses collection, and the
corresponding foreign key property on the course object is set to the
key property value of the department.
course.Department = department;
But as you observed, this only happens after you call SaveChanges or one of the other actions mentioned in the "Synchronizing the changes between the FKs and Navigation properties" portion of the document linked above.
If you are using POCO entities without proxies, you must make sure
that the DetectChanges method is called to synchronize the related
objects in the context. Note, that the following APIs automatically
trigger a DetectChanges call.
DbSet.Add
DbSet.Find
DbSet.Remove
DbSet.Local
DbContext.SaveChanges
DbSet.Attach
DbContext.GetValidationErrors
DbContext.Entry
DbChangeTracker.Entries
Executing a LINQ query against a DbSet
If this is not happening at all, my guess is that you haven't properly defined StoreID as the foreign key of the navigation property Store.
I just started looking at Database Views with Code First... and try to decide if I should use them.
Here Ladislav recommends to use NotMapped inheritance parent for table and Db-View (my view only adds sums of child entities)... but how this work with CF Migrations? I really want to use them.
Also... navigation properties will work on Db-View Entity?
Is there any way to save data directly into Db-View entity (and it's table)?
If you want to use code first and migrations you should not use views. Views are database "logic" constructs and code first is not an approach for creating database logic. With code first you should use the projection which is also mentioned in the linked answer.
Migrations will not be able to detect changes related to your views. You will have to write all migration code for views manually.
If you want to use views you should do database first (= no migrations) and either map them with EDMX or code mapping.
Also... navigation properties will work on Db-View Entity?
This is the only scenario where code mapping provides better support than EDMX. You can define relation in your model even if it doesn't exist in the database (but your database must ensure data integrity). It is in theory possible with EDMX as well but it requires changing EDMX manually.
Is there any way to save data directly into Db-View entity (and it's table)?
Yes but your view must be updatable. I don't think that view with aggregation values is updatable.
I am using the Service Layer --> Repository --> Entity Framework (Code-First) w/POCO objects approach, and I am having a hard time with updating entities.
I am using AutoMapper to map my Domain Objects to my View Models and that works good for getting the data, no how do I get that changes back into the database?
Using pure POCO objects, I would assume that there is no sort of change tracking, so I see my only option is to handle it myself. Do you just make sure that your View Models have the EXACT same properties as your Domain Objects? What if I just change a field or two on the View Model? Won't the rest of the fields on the Domain Object get overwritten in the database with default values?
With that said, what is the best approach?
Thanks!
Edit
So what I am stumbling on is this, lets take for example a simple Customer:
1) The Controller has a service, CustomerService, that calls the services GetCustmoerByID method.
2) The Service calls into the CustomerRepository and retrieves the Customer object.
3) Controller uses AutoMapper to map the Customer to the ViewModel.
4) Controller hands the model to the View. Everything is great!
Now in the view you do some modifications of the customer and post it back to the controller to persist the changes to the database.
I would assume at this point the object is detached. So should the model have the EXACT same properties as the Customer object? And do you have to make hidden fields for each item that you do not want to show, so they can persist back?
How do you handle saving the object back to the database? What happens if your view/model only deals with a couple of the fields on the object?
If you're using EF Code First, i.e: the DbContext API, then you still do have change tracking which is taken care of by your context class.
after making changes to your objects, all you have to do is call SaveChanges() on your context and that will persist the changes to your database.
EDIT:
Since you are creating a "copy" of the entity using AutoMapper, then it's no longer attached to your context.
I guess what you could do is something similar to what you would in ASP.NET MVC (with UpdateModel). You can get the original entity from your context, take your ViewModel (which may contain changed properties) and update the old entity, either manually (just modified properties), or using AutoMapper. And then persist the changes using context.SaveChanges().
Another solution would be to send the model entity as [part of] the ViewModel. This way, you'll have your entity attached to the container and change tracking will still work.
Hope this helps :)
You are absolutely right that with a detached object you are responsible for informing the context about changes in your detached entity.
The basic approach is just set the entity as modified. This works for scalar and complex properties but it doesn't work for navigation properties (except FK relations) - for further reading about problems with navigation properties check this answer (it is related to EFv4 and ObjectContext API but same problems are with DbContext API). The disadvantage of this approach is that all fields in DB will be modified. If you just want to modify single field you still have to correctly fill others or your database record will be corrupted.
There is a way to explicitly define which fields have changed. You will set the modified state per property instead of whole entity. It is little bit harder to solve this on generic approach but I tried to show some way for EFv4 and for EFv4.1.
I agree with #AbdouMoumen that it's much simpler to use the model entities at the view level. The service layer should provide an API to persist those entities in the data store (db). The service layer shouldn't dumbly duplicate the repository lawyer (ie: Save(entity) for every entity) but rather provide a high level save for an aggregate of entities. For instance, you could have a Save(order) in the service layer which results in updating more basic entities like inventory, customer, account.
I'm after some opinions \ best practice for handling updates to my repository in the following scenario:
I am using EF 4 with the POCO tt templates which creates nice clean clr objects.
For example's sake lets say I have a POCO object name Customer and a ViewModel called CustomerViewModel. CustomerViewModel has a public property for the Customer object which is populated with the POCO Customer object.The view references the Customer object on the CustomerViewModel. So far so good. Everything is displayed as expected.
When it comes time to update the CustomerViewModel is passed back and only the properties that were bound to the view are populated, fair enough.
What I have now is a POCO object that is missing some of the property values which are needed to update via the EF data context. For example, since I did not display the ID in the view, it was not hydrated back into the view model's Customer property. Not really surprising behaviour but I am wondering what the best way to handle this scenario is.
So here is the question:
Would it be better to map the properties that i don't display into hidden fields so that I have the complete POCO object on postback which is ready for updating to the Repository? (I'm thinking there is needles sending of data to and from the client here)
OR should I do a read of Customer before my update(assuming I have the ID) and then update the properties from my view model object. ( is this a needles read on the database ?).
OR is there another may altogether that I am missing.
I realise that maybe there is no one correct answer for this but I'd be interested to hear how others are handling this scenario.
Thanks
I'm going to answer my own question here... maybe it was a silly question but the act of writing it out has made the answer more obvious..
The first option of populating hidden fields is a bad idea for too many reasons!! So I think I'll have to go with doing a read of the customer object on the post back and calling.
TryUpdateModel(customer, "Customer");
Where customer is the freshly read Customer and "Customer" is the property name on the view model.
It seems that this results in more data access than in a classic ASP where the object could have been shoved (rightly or wrongly) into Session !
Anyone care to add their 2c ?
It appears to me that a strange phenomenon is occurring with inherited entities (TPT) in EF4.
I have three entities.
1. Asset
2. Property
3. Activity
Property is a derived-type of Asset.
Property has many activities (many-to-many)
When modeling this in my EDMX, everything seems fine until I try to insert a new Property into the database. If the property does not contain any Activity, it works, but all hell breaks loose when I add some new activities to the new Property.
As it turns out after 2 days of crawling the web and fiddling around, I noticed that in the EF store (SSDL) some of the constraints between entities were not picked up during the update process.
Property_Activity table which links properties and activities show only
one constraint
FK_Property_Activity_Activity but
FK_Property_Activity_Property was
missing.
I knew this is an Entity Framework anomoly because when I switched the relationship in the database to:
Asset <--> Asset_Activity <--> Activity
After an update, all foreign key constraints are picked up and the save is successful, with or without activities in the new property.
Is this intended or a bug in EF?
How do I get around this problem?
Should I abandon inheritance altogether?
Not a but but a poor visual designer.
Its generally best to simply manage the Entity XML by hand.
No inheritance works well for many situations.
Basically I use the update from database in the visual designer but knowing that the designer has its quirks. I have simply used the update from database to stub out the basics of what I want. Then I go into the Entity XML my self and clean it up the way I want. Just of note Complex types are a pain with the designer. If you plan to use complex types get ready to learn your Entity XML well.