Some objects not materializing (but are in query response) - inheritance issue? - breeze

I've just added a fourth layer of expand to my query - ie:
.expand("..., ScanDates.Printouts.BMDSites, ...");
And I've discovered that although the data is being returned in the response, it is not populating the objects below "Printouts" (ie. patient.ScanDates.Printouts.BMDSites is an empty array, despite several elements being returned in the response).
I've altered the MaxExpansionDepth on the controller action, and there are no errors appearing on the console or server side. I've also successfully filled BMDSite objects by just querying for them individually, but that would mean ten or twenty return trips to the server... not ideal.
Edit: I've just tried several other queries, and it seems that even if I'm just doing a single expand (ie: .expand("BMDSites")), the same problem occurs - data is in response, but not materialized into entities. When I query just for the BMDSites, (say for a specific Printout) the array is filled and materialized properly.
Edit 2: It just occurred to me that the Printout class is the base class of a TPH inheritance hierarchy... Looking around a bit, I suspect that this is likely the source of the issue.
Thanks so much for any ideas!
-Brad

Looks like it had nothing to do with inheritance after all... In creating a simplified model for Jay, I of course found that it worked just fine. Adding back in the features that I thought were irrelevant, I eventually broke it, and replicated my issue by adding in some [NotMapped] properties that were providing some easy access to the list of BMDSites. For example, in a class derived from Printout:
[NotMapped]
public BMDSite _Ud = null;
[NotMapped]
public BMDSite Ud
{
get
{
if (_Ud == null)
{
_Ud = BMDSites.Find(b => b.Region == Region.Forearm_UD);
}
return _Ud;
}
}
Upon adding this back in, once again, my list of BMDSites were not populating (edit- more specifically, any BMDSite that was touched by an unmapped property was being excluded from the list of BMDSites). Turns out that the JSON.net classes that Breeze uses don't look at [NotMapped] (which makes sense, as it is serialization, not DB mapping)... By adding a reference to JSON.net in my EF model, and adding it's equivilent tag - ie: [NotMapped, JsonIgnore], it doesn't look at the properties, and everything works just fine.
Bottom line (for those that skim)... code above causes issues, code below works fine:
[NotMapped, JsonIgnore]
public BMDSite _Ud = null;
[NotMapped, JsonIgnore]
public BMDSite Ud
{
get
{
if (_Ud == null)
{
_Ud = BMDSites.Find(b => b.Region == Region.Forearm_UD);
}
return _Ud;
}
}
Cheers,
Brad

I would start by insuring that the 'expand' you are doing is in fact valid by trying the exact same query on the server using 'Include's. If this fails then the issue is likely with your model. Breeze 'expand's get turned into EF 'Include's.
If the query works in pure EF, then can you detail the relevant properties in your model and what the inheritance hierarchy looks like so that we can try to replicate your issue?

Related

Add to DB using SaveChanges() in Entity Framework with object from another scope

I'm new using entity framework, and I'm trying to insert into the DB.But I'm having an issue, because I need to only SaveChanges from objects of other 3 scopes. Like this:These are my three Actions that Add the objects into my entities:
public void AddEndereco(entidade_endereco entEndereco)
{
db.entidade_endereco.Add(entEndereco);
}
public void addContato(entidade_contato entContato)
{
db.entidade_contato.Add(entContato);
}
public void addBanco(entidade_banco entBanco)
{
db.entidade_banco.Add(entBanco);
}
And in this action I need to insert all the objects into my DB:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(entidade entidade, string Grupo, string Situacao)
{
if (ModelState.IsValid)
{
if (Grupo != "")
entidade.gre_codigo = Convert.ToInt32(Grupo);
if (Situacao != "")
entidade.sie_codigo = Convert.ToInt32(Situacao);
if (entidade.ver_ativo)
entidade.ent_ativo = "S";
else
entidade.ent_ativo = "N";
if (entidade.ver_cliente)
entidade.ent_cliente = "S";
else
entidade.ent_cliente = "N";
if (entidade.ver_fornecedor)
entidade.ent_fornecedor = "S";
else
entidade.ent_fornecedor = "N";
//ADDING ANOTHER OBJECT
db.entidades.Add(entidade);
//HERE IS WHERE I NEED TO SAVE ALL (entidade_endereco, entidade_contato, entidade_banco, entidade)
db.SaveChanges();
return RedirectToAction("Index");
}
return View(entidade);
}
But it is only saving the entidade object, the others don't exist anymore when db.SaveChanges() is executed.
How can I insert into the DB with objects that were added to my entity in other scopes?
If you really want to make this work as is, you would need to store either the Context (really bad idea) or Entities (slightly less bad) across requests. Session State jumps to mind, but using it can bring in a whole load of new pain.
Ideally, you should change your design to take advantage of the stateless nature of HTTP. Each action method should be a separate transaction, saving the data from it's execution when the method is done. If those separate entities only make sense when they are all saved together, then you need to create all of them within a single action and save them to the context together. Managing the boundaries of different business entities and when they are saved is a critical part of application design, I highly recommend you read about Aggregate Roots within Domain Driven Development. Even if you don't go the full DDD route, the Aggregate Root concept will be extremely helpful to you. The CQRS Journey from Microsoft gives an in-depth tutorial of these concepts (and many others)
Im not sure, if I got your question right (excuse my poor spanish). In the Action Create you only add "entidade" to your entidades collection, and so its the only one affected by SaveChanges(). If you want to add others, include in the Create-Action or try making a EF-transaction.
Without transaction the context is lost after the Create-Method ends

Deep expand not working, despite [BreezeQueryable(MaxExpansionDepth = 100)]

First off, I really have to thank the devs so much... Breeze is absolutely fantastic, and I can't thank you enough for your hard work!
I've been using Breeze with EF (latest Breeze, latest EF) for a while now, and after some DB changes, I'm now forced to query for a fourth layer of objects... At first, I hit the error that the MaxExpansionDepth was reached, but as per a few questions/answers on SO, I found the [BreezeQueryable(MaxExpansionDepth = x)] attribute. I have applied this attribute to the relevant query function on the controller, which eliminated the error... However, the data at that fourth level still does not fill.
I have successfully retrieved the data in question with a specific query (based on the key of the 4rth level data), and everything works well when playing on the server side... Relationships work properly etc... The troublesome query is below:
function getPatient(patKey) {
var query = breeze.EntityQuery
.from("Patients")
.where("Key", "==", patKey)
.expand("..., ScanDates.Printouts.BMDSites, ...");
return app.dataservice.manager.executeQuery(query);
}
BTW - this is all for a single patient, so there really isn't that much data - it's just compartmentalized quite a bit!
If anybody has any ideas, I'd be terribly grateful!
Cheers,
Brad
P.S.: Obviously, I don't need a "MaxExpansionDepth = 100", but I've also tried with low values (4,5,etc)
Edit: Thanks to Dominictus, I now realize that the real problem isn't the depth of the query - the BMDSites are coming back in the response, but not materializing entities regardless of expand depth. They do materialize if I query just for them (ie BMDSites where PrintoutKey = x)... but again, this is causing ten or 15 trips to the server. I'd still love to know how to get everything at once, or just learn why these won't materialize on an expand!
Edit 2: It just occurred to me that the Printout class is the base class of a TPH inheritance hierarchy... Looking around at some of the other questions, I suspect that this is likely the source of the issue.
Turns out it had nothing to do with inheritance, or the depth of the expand... In creating a simplified model, I of course found that it worked just fine. Adding back in the features that I thought were irrelevant, I eventually broke it, and replicated my issue by adding in some [NotMapped] properties that were providing some easy access to the list of BMDSites. For example, in a class derived from Printout:
[NotMapped]
public BMDSite _Ud = null;
[NotMapped]
public BMDSite Ud
{
get
{
if (_Ud == null)
{
_Ud = BMDSites.Find(b => b.Region == Region.Forearm_UD);
}
return _Ud;
}
}
Upon adding this back in, once again, my list of BMDSites were not populating. Turns out that the JSON.net classes that Breeze uses don't look at [NotMapped] (which makes sense, as it is serialization, not DB mapping)... By adding a reference to JSON.net in my EF model, and adding it's equivilent tag - ie: [NotMapped, JsonIgnore], it doesn't look at the properties, and everything works just fine.
Bottom line (for those that skim)... code above causes issues, code below works fine:
[NotMapped, JsonIgnore]
public BMDSite _Ud = null;
[NotMapped, JsonIgnore]
public BMDSite Ud
{
get
{
if (_Ud == null)
{
_Ud = BMDSites.Find(b => b.Region == Region.Forearm_UD);
}
return _Ud;
}
}
Cheers,
Brad
If you use some other queries to Patients action, I suggest you copy Patients method, name it something like PatientsFull and in there do .Include instead of clientside expand. Sometimes expands don't work as expected. (If this is the only query to Patients then just change that method)
For some different ideas you would have to write down any possible errors that pop into console.

mvc in asp.net doesnt satisfy programmers

I am learning MVC4 in Visual Studio and I have many questions about it. My first statement about MVC is that MVC's Model doesnt do what I expected. I expect Model to select and return the data rows according to the needs.
But I read many tutorial and they suggest me to let Model return ALL the data from the table and then eliminate the ones I dont need in the controller, then send it to the View.
here is the code from tutorials
MODEL
public class ApartmentContext : DbContext
{
public ApartmentContext() : base("name=ApartmentContext") { }
public DbSet<Apartment> Apartments { get; set; }
}
CONTROLLER
public ActionResult Index()
{
ApartmentContext db = new ApartmentContext();
var apartments = db.Apartments.Where(a => a.no_of_rooms == 5);
return View(apartments);
}
Is this the correct way to apply "where clause" to a select statement? I dont want to select all the data and then eliminate the unwanted rows. This seems weird to me but everybody suggest this, at least the tutorials I read suggest this.
Well which ever tutorial you read that from is wrong (in my opinion). You shouldn't be returning actual entities to your view, you should be returning view models. Here's how I would re-write your example:
public class ApartmentViewModel
{
public int RoomCount { get; set; }
...
}
public ActionResult Index()
{
using (var db = new ApartmentContext())
{
var apartments = from a in db.Apartments
where a.no_of_rooms == 5
select new ApartmentViewModel()
{
RoomCount = a.no_of_rooms
...
};
return View(apartments.ToList());
}
}
Is this the correct way to apply "where clause" to a select statement?
Yes, this way is fine. However, you need to understand what's actually happening when you call Where (and various other LINQ commands) on IQueryable<T>. I assume you are using EF and as such the Where query would not execute immediately (as EF uses delayed execution). So basically you are passing your view a query which has yet to be run and only at the point of where the view attempts to render the data is when the query will run - by which time your ApartmentContext will have been disposed and as a result throw an exception.
db.Apartments.Where(...).ToList();
This causes the query to execute immediately and means your query no longer relys on the context. However, it's still not the correct thing to do in MVC, the example I have provided is considered the recommended approach.
In our project, we will add a Data Access Layer instead of accessing Domain in controller. And return view model instead of Domain.
But your code, you only select the data you need not all the data.
If you open SQL Profiler you'll see that's a select statement with a where condition.
So if it's not a big project I think it's OK.
I can't see these tutorials but are you sure it's loading all the data? It looks like your using entity framework and entity framework uses Lazy laoding. And Lazy loading states:
With lazy loading enabled, related objects are loaded when they are
accessed through a navigation property.
So it might appear that your loading all the data but the data itself is only retrieved from SQL when you access the object itself.

EF Reference gets lost when Web API returns IQueryable

I have been looking for quite some time now on this problem.
Here's the deal.
I'm building a website that calls to a Web API to get its data. My Web API uses a library, working with repository pattern. My database model (EF Model-first) was build in the library. In that model I have a base class Pass. Then I have two derived classes, CustomerCard : Pass and Voucher : Pass. My model from EF Designer
I have a method to get all the CustomerCards.
public IQueryable<CustomerCard> GetAllPasses() {
IList<CustomerCard> allCards = new List<CustomerCard>();
var c_cards = context.Passes;
foreach (var c_card in c_cards) {
if (c_card is CustomerCard) {
allCards.Add((CustomerCard)c_card);
}
}
return allCards.AsQueryable<CustomerCard>();
}
In my ApiController, I use this method to get the passes and return them to the website, like this:
[HttpGet]
[Queryable]
public IQueryable<CustomerCard> GetAllPasses(string version) {
return passRepo.GetAllPasses().AsQueryable();
}
My Web API returns JSON format. This is my config to preserve referencing and stuff:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.Remove(config.Formatters.XmlFormatter);
I'm using IQueryable because I want to be able to page the data on my website. The api method is available at '/api/v1/passes/all'.
Here's the strange part. To test my paging, I call 1 pass per page.
For my first Pass, it works fine. But when I go to my second page, he also gets the correct pass, but the reference to User is gone.
As you can see in my model, the CustomerCard class has a property User. This indicates who owns the customer card.
So this call loads the user from the pass: 'api/v1/passes/all?$top=1'
but when I call to this one, the user instance is NULL: 'api/v1/passes/all?$top=1&$skip=1'.
However, when I call to 'api/v1/passes/all?$top=2', the User for the second pass IS loaded.
So this is where my mind get's blown! I don't get it? Why doesn't the user-reference comes along with the second one? Could it have something to do with the Lazy loading feature of the EF?
EDIT
When I use the extension method Include on context.passes, an error is thrown:
A specified Include path is not valid. The EntityType 'LCS_Model.Pass'
does not declare a navigation property with the name 'User'.
This is because Passes as a dbset, contains CustomerCard as well as Voucher. Is there a way I can tell my context to expect or convert it to a CustomerCard?
Can someone please help me. If you don't understand my question, ask away!
Thanks allready!
EDIT 2
The method on my API controller is now
[HttpGet]
[Queryable]
public IQueryable<CustomerCard> GetAllPasses(string version) {
return context.Passes.Include("User").OfType<CustomerCard>();
}
This gives me my correct items. I have 2 customer cards in my db. Both are from the same user. My API has the user still loaded. The moment my website receives the response, the User property becomes null. My guess is that it's because it is still referencing to the same user from the first element of the array. Is that possible? And if yes, how can I prevent that from happening?
Yes, you need to make sure any related records are included when you do your query. See this for some examples. Secondly... I fail to understand why you are doing all that work with the for loop... That's a lot of absolutely needless and wasted work for the server to do if you want to do any paging. I'm thinking, besides any other filters you might want to apply, your GetAllPasses should look something like this.
public IQueryable<CustomerCard> GetAllPasses() {
return context.Passes.Include(r => r.User);
}
Edit (2): I need to read better. I have to confess, I'm not familiar with type inheritance in EF. I found some things that might work here: table per hierarchy, table per concrete type, and see also also MSDN Queryable.OfType<TResult>. This is a guess, but let's try:
public IQueryable<CustomerCard> GetAllPasses() {
return context.Passes.OfType<CustomerCard>().Include(r => r.User);
}

Constrain the number of child entities in Entity Framework

Bottom Line Up Front
Is there a succinct way that I can constrain the number of child entities that can belong to a parent in Entity Framework. I am using 4.3.1 at the moment.
The Problem
I am developing an ASP.NET MVC3 site which accesses data via a data access layer that uses Entity Framework. I have a SearchList entity which has a many to many relationship to a Search entity. A SearchList may have many Searches, and a Search may belong to many SearchLists.
At one point in the workflow of the site, a user needs to select the searches and other items to use in a batch search. We want the page to load the entire search list.
SearchLists can get quite large, and as a test we created one with 21,000 searches. It took a few seconds, and the data returned was about 9.5 MB, which we were expecting, but jQueryUI choked when trying to table-ify that much.
What we would like
So we want to impose a limit on the number of searches any search list can have. I can go through the application and put a bunch of rules in that checks the size of the collection and if the searches that are trying to be added plus the size of the current... yada yada yada.
If however there was a better way (especially one that could easily output an error message that MVC would pick up) I would totally take that instead.
I have googled, and perused a number of EF blogs to no avail. Constrain children and max number of children in collection and similar searches have returned results that are about Linq queries and the Count and Max methods.
Any help would be appreciated.
There is no built-in way so you will have to code such validation yourselves. Some quick ideas:
You can for example use custom collection for the navigation property which will fire exception when you try to add additional search exceeding the threshold. It is simple but it demands you to have all searches loaded, it will have concurrency problems and moreover it can fire during loading search list and searches from database.
You can handle it in overriden SaveChanges. You will at least have to check how many searches are already related to search list but you will still have concurrency problem (what if other request tries to add search to the same list but only one place is remaining - both can succeed the check and insert related search)
You can handle it in database trigger - again it will have concurrency problems
Avoiding concurrency problems completely requires hand written queries with locking hints to ensure that only one request can check number of searches per search list and insert a new search in atomic transaction.
I ended up going with CustomValidationAttribute, and implemented it with a great deal of success. See below for my implementation info:
In the SearchList entity
[NotMapped]
public String ValidationMessage { get; set; }
[CustomValidation(typeof(EntityValidation.EntityValidators), "ValidateSearchCount")]
public virtual List<Search> Searches { get; set; }
public static bool Create(ProjectContext db, SearchList searchList)
{
try
{
db.SearchLists.Add(searchList);
db.SaveChanges();
return true;
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
searchList.ValidationMessage += validationError.ErrorMessage;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
EntityValidators Class
public static ValidationResult ValidateSearchCount(List<Search> Searches)
{
bool isValid;
int count = Searches.Count();
isValid = (count <= 5000 ? true : false);
if (isValid)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("A maximum of 5000 searches may be added to a SearchList.");
}
}
A similar exception block is on the update method. In this way, when SaveChanges gets called it attempts to validate the entity and its child collections, and when the collection count is greater than 5000 the validator will return an error message which gets caught in the exception handler and stored in a local property for my controller to check when things go wrong.

Resources