Using navigation properties in entity framework code first - entity-framework-4

Context:
Code First, Entity Framework 4.3.1;
User ---- Topic, 1 to Many relation;
User with public virtual ICollection<Topic> CreatedTopics Navigation Property(Lazy Loading);
Topic with public virtual User Creator Navigation Property;
DataServiceController : DbDataController<DefaultDbContext>, Web API beta, ASP.NET MVC 4 Beta , Single Page Application;
System.Json for Json serialization;
Web API Action:
public IQueryable<Topic> GetTopics()
{
// return DbContext.Topics; // OK
return DbContext.Topics.Include("Creator"); //With Exception
}
Result: "an unhandled microsoft .net framework exception occurred in w3wp.exe"
The Problem here seems to be: I should not Add Navigation Property in both Entities(Cause Circular Reference?), and if I delete the CreatedTopics Navigation Property in User Class, It will be OK again.
So, In a similar Context like listed above, Here are my questions:
How to deal with Navigation Properties in the situation of 1 to Many relation;
Further more, how about a Many to Many relation, do i have to divide it into two 1 to Many relations;
What is the Best Practices and Precautions of using Navigation Properties?
I Have read many related posts, but still not clear enough :(,
Thanks for any help!
Dean

This is not a problem of code first or EF - it is a problem of serialization. Simply the serializer used to convert your object graph to some representation passed in a Web API message is not able to work with circular references by default. Depending on the message format you want to use Web API uses different serializers by default - here is more about default serializers used by Web API and about the way how to change it. The following text suppose that you are using DataContractJsonSerializer or DataContractSerializer (should be default for XML serialization) but the same is possible for JSON.NET (should be default for JSON serialization - JSON serialization can be switched to DataContractJsonSerializer but the default serializer is better).
So what you can do? You can tell the serializer that it should track those circular references by marking your classes with DataContract(IsReference = true) and each passed property with DataMember attribute (check the linked article for description how to achieve it with JSON.NET). This will allow serializer correctly recognizing cycles and the serialization will in theory succeed. In theory because this also demands to not using lazy loading. Otherwise you can serialize much more data than you expected (in some catastrophic scenarios it can lead to serializing whole content of your database).
When you serialize entity graph with lazy loading enabled you serailze a Topic and its Creator but serialization will also visit CreatedTopics property => all related topics are lazy loaded and processed by serialization and serialization continues to visit Creator of all newly loaded topics! This process continues until there is no other object to lazy load. Because of this you should never use lazy loading when serializing entities.
Other option is to exclude back reference from serialization. You just need to serialize Creator. You don't need to serialize CreatedTopics so you can mark the property with IgnoreDataMember attribute (JsonIgnore for JSON.NET). The problem is that if you also have Web API action for returning User with all his CreateTopics this will not work because of the attribute.
The last option is not using entities. This option is usually used in web services where you create special DTO objects satisfying requirements for specific operation and you handle conversion between entities and DTOs inside the operation (possible with help of some tool like AutoMapper).
There is no difference between handling one-to-one, one-to-many, or many-to-many relations. If you have navigation properties on both sides you must always deal with this problem.

Related

Populate model properties inside of the model

I'm developing a webpage in MVC 5 and have been developing in MVC quite sometime now.
I always try/want to learn new ways/best practice of my programming skills. Right now I just stumbled upon something with ViewModels.
For example, I'm using the same ViewModel for multiple pages where I have Dictionary properties to fill my drop down lists.
So normally what I have done is creating a private method in the controller like "SetupViewModel" and then populate the dictionary to the model properties there and inside the model constructor just a "failsafe" creating an empty dictionary.
But for this project I'm working on now I thought that I would try to directly in the model constructor call my service method that returns the list for the ddl and then populate it right there.
Is there any advantages or disadvantages doing this way. What would you say is best practice? Because I can see some problems like, if the database goes down I could still load the page with empty values if I have the "setupViewModel"- method in the controller and with some try/catch or something preventing crash and if it is in the VM it would crash directly if I don't add some fail-safe in the services like returning empty lists if I can't get anything from the DB.
So it's equally much development but at different locations (well I can always have some fail-safe in the service ofc).
But the main question is, what is the best practice, populate model properties from model or controller?
Personally in MVC I see accessing the data layer as a model concern. Controllers are supposed to do as little as possible. So ideally I would in the constructor first initialise the dictionary to an empty one, then in a try..catch (which does nothing on error) get the database value for the dictionary and set it again.

complex hierarchy updates based on form input

I am trying to understand the best way to work with complex hierarchies of objects that i manipulate based on data on forms in Grails.
I cannot use the command object as my form is dynamic (users can add any number of records). I am told we should parse the params in controller and let services do the transaction activities on the domain objects and thus reduce coupling. Sometimes this doesn't seem straightforward.
I have a few lists of child domain objects in a base domain object that is being 'updated' which means the list could have grown or reduced, meaning some domain tuples will need to be added/removed, how do i pass that information from controller to service without making a function with 8 parameters? If anyone has any strategies you've used, please share. I am sure this is not uncommon but I haven't seen any discussions on such a question.
e.g.
class DomainA {
List<DomainB> bList
List<DomainC> cList
DomainD domD
}
class DomainD {
List<DomainE> elist
}
How about relying on ajax. You might save classD and then class A, or use a command object to save both. Then with the Id´s of these two classes you might add everything else you need using ajax.

breezejs + entity framework: how to round-trip ad-hoc properties

I'm using breezejs with an entity framework 5 model. The model is the old-school edmx/objectcontext style- not the newer dbcontext/poco style.
The model is shared with some wcf ria services domain services so I cannot switch to entity framework 6 or poco style entity framework at this time.
When using wcf ria services, if you wanted to add a property to an entity beyond what is generated by entity framework you could create a partial class, define the property and annotate it with the datamember attribute. Wcf ria services treats this new property like any other property and sends it to the client from the server and back to the server.
Is there a way to do the same thing with breezejs? Without moving entirely away from the automatic metadata generation goodness that comes with using entity framework?
Using fiddler I can see the property I want exposed is transmitted to the client during a query request.
I've looked at the documentation here http://www.breezejs.com/documentation/extending-entities but none of the examples seem to fit this scenario.
Breeze supports unmapped properties, these are properties that are declared on your javascript constructor that cannot be matched to any property in metadata. By default these properties are both persisted locally and sent to the server on a save. This is described in the link you mentioned:
http://www.breezejs.com/documentation/extending-entities
var Customer = function () {
this.myUnmappedProperty = "anything22";
};
myEntityManager.metadataStore.registerEntityTypeCtor("Customer", Customer);
These values will be available on the server after a SaveChanges call via the 'UnmappedValuesMap' property on each EntityInfo instance.
var unmappedValue = entityInfo.UnmappedValuesMap["myUnmappedProperty"];
What is sounds like you are looking for is "unmapped" properties to go in the "other" direction, i.e. from the server to the client. What might work for that but we haven't tried is adding a property to your server side EF class ( via the partial class mechanism) and mark it up for Json serialization. It "should" then get serialized down to the client, even though it won't show up in Metadata.
If this does NOT work, please post back here and we will consider it as a breeze feature request. The basic idea does make a lot of sense and we should support it.

Model binding to DataTable with no underlying database

I am bootstrapping myself through my very first ASP MVC project, and could use some suggestions regarding the most appropriate (data-side) model binding solution I should pursue. The project is 'small', which really just means I have very limited time for chasing down dead-ends, which cramps my available learning curve. Thanks heaps for reading!
Background: a simple address search app (ASP.NET MVC 3) that sends user form input to a vendor-sourced server, and presents the results returned from the server in a rules-driven format. There is no CRUD-style repository as such; this is an entirely read-only application. The vendor's .NET server API specifies the use DataTable objects (System.Data.DataTable) for both requests and replies.
Currently: I have a prototype under construction to validate server behavior and inform the application's design. There is a conventional MVC data model class for the input form which works great, auto-binding with the view just as you'd expect. When submitted, the controller passes this input model to my vendor API wrapper, which is currently binding to the request table medieval-style:
public DataTable GetGlobalCandidateAddresses(AddressInputModel input)
{
...
DataRow newRow = dataTable.NewRow();
newRow[0] = input.AddressLine1;
newRow[1] = input.AddressLine2;
newRow[2] = input.AddressLine3;
...
dataTable.Rows.Add(newRow);
...
This works fine; the inputs are fixed and have very light validation requirements. However, if there is a modern framework solution for quickly reflecting a DataTable from my model, that would be peachy.
My real conundrum, however, is on the reply. The table returned by the server contains a variable column-set, with any combination of at least 32 possible unordered fields on a per-transaction basis. Some of the column names contain compiler-invalid characters ("status.description") that won't map literally to a model property name. I will also have a need to dynamically map or combine some of the reply fields in the view model, based on a series of rules (address formats vary considerably by country), so not all fields are 1-to-1.
Just to get the prototype fired up and running, I am currently passing the reply DataTable instance all the way back to a strongly-typed view, which spins it out into the display exactly as is. This is nice for quickly validating the server replies, but is not sufficient for the real app (much less satisfying best practices!).
Question: what is my best tooling approach for binding DataTable rows and columns into a proper model class for display in a view, including some custom binding rules, where no underlying database is present?
Virtually all of the training materials I am consuming discuss classic database repository scenarios. The OnModelCreating override available in the Entity Framework seems ideal in some respects, but can you use a DBContext without a DB connection or schema?
If I have to roll my own model binder, are there any tricks I should consider? I've been away from .NET for a while (mostly Java & SQL), so I'm picking up LINQ as I go as well as MVC.
Thanks again for your attention!
Create a poco display model AddressDisplay and do custom object mapping from the data table to the display model. You can use data annotations for formatting but you can also do that in your custom mapping. You shouldn't need to create a custom model binder.
So create two poco models, AddressInput and AddressDisplay, you can use data annotations on AddressInput for validation. When AddressInput is posted back, map it to the outbound data table. When the response is received, map the inbound data table to AddressDisplay and return the view to the user.

How to handle view model with multiple aggregate roots?

At the moment, i got quite badly fashioned view model.
Classes looks like this=>
public class AccountActionsForm
{
public Reader Reader { get; set; }
//something...
}
Problem is that Reader type comes from domain model (violation of SRP).
Basically, i'm looking for design tips (i.e. is it a good idea to split view model to inputs/outputs?) how to make my view model friction-less and developer friendly (i.e. - mapping should work automatically using controller base class)?
I'm aware of AutoMapper framework and i'm likely going to use it.
So, once more - what are common gotchas when trying to create proper view model? How to structure it? How mapping is done when there's a multiple domain object input necessary?
I'm confused about cases when view needs data from more than 1 aggregate root. I'm creating app which has entities like Library, Reader, BibliographicRecord etc.
In my case - at domain level, it makes no sense to group all those 3 types into LibraryReaderThatHasOrderedSomeBooks or whatnot, but view that should display list about ordered books for specific reader in specific library needs them all.
So - it seems fine to create view OrderedBooksList with OrderedBooksListModel view model underneath that holds LibraryOutput, ReaderOutput and BibliographicRecordOutput view models. Or even better - OrderedBooksListModel view model, that leverages flattening technique and has props like ReaderFirstName, LibraryName etc.
But that leads to mapping problems because there are more than one input.
It's not 1:1 relation anymore where i kick in one aggregate root only.
Does that mean my domain model is kind a wrong?
And what about view model fields that live purely on UI layer (i.e. enum that indicates checked tab)?
Is this what everyone does in such a cases?
FooBarViewData fbvd = new FooBarViewData();
fbvd.Foo = new Foo(){ A = "aaa"};
fbvd.Bar = new Bar(){ B = "bbb"};
return View(fbvd);
I'm not willing to do this=>
var fbvd = new FooBarViewData();
fbvd.FooOutput = _mapper.Map<Foo,FooOutput>(new Foo(){ A = "aaa"});
fbvd.BarOutput = _mapper.Map<Bar,BarOutput>(new Bar(){ B = "bbb"});
return View(fbvd);
Seems like a lot of writing. :)
Reading this at the moment. And this.
Ok. I thought about this issue a lot and yeah - adding another abstraction layer seems like a solution =>
So - in my mind this already works, now it's time for some toying.
ty Jimmy
It's tough to define all these, but here goes. We like to separate out what we call what the View sees from what the Controller builds. The View sees a flattened, brain-dead DTO-like object. We call this a View Model.
On the Controller side, we build up a rich graph of what's needed to build the View Model. This could be just a single aggregate root, or it could be a composition of several aggregate roots. All of these together combine into what we call the Presentation Model. Sometimes the Presentation Model is just our Persistence (Domain) Model, but sometimes it's a new object altogether. However, what we've found in practice is that if we need to build a composite Presentation Model, it tends to become a magnet for related behavior.
In your example, I'd create a ViewFooBarModel, and a ViewFooBarViewModel (or ViewFooBarModelDto). I can then talk about ViewFooBarModel in my controller, and then rely on mapping to flatten out what I need from this intermediate model with AutoMapper.
Here's one item that dawned on us after we had been struggling with alternatives for a long time: rendering data is different from receiving data.
We use ViewModels to render data, but it quickly turned out that when it came to receiving data through forms posting and similar, we couldn't really make our ViewModels fit the concept of ModelBinding. The main reason is that the round-trip to the browser often involves loss of data.
As an example, even though we use ViewModels, they are based on data from real Domain Objects, but they may not expose all data from a Domain Object. This means that we may not be able to immediately reconstruct an underlying Domain Object from the data posted by the browser.
Instead, we need to use mappers and repositories to retrieve full Domain Objects from the posted data.
Before we realized this, we struggled much with trying to implement custom ModelBinders that could reconstruct a full Domain Object or ViewModel from the posted data, but now we have separate PostModels that model how we receive data.
We use abstract mappers and services to map a PostModel to a Domain Object - and then perhaps back to a ViewModel, if necessary.
While it may not make sense to group unrelated Entities (or rather their Repositories) into a Domain Object or Service, it may make a lot of sense to group them in the Presentation layer.
Just as we build custom ViewModels that represents Domain data in a way particularly suited to a specific application, we also use custom Presentation layer services that combine things as needed. These services are a lot more ad-hoc because they only exist to support a given view.
Often, we will hide this service behind an interface so that the concrete implementation is free to use whichever unrelated injected Domain objects it needs to compose the desired result.

Resources