Breeze: Unable to locate property: XYZ on type:YYY when executing executeQuery on entity manager - entity-framework

I'm trying to get data from my Webapi2 Breeze controller with Entity Framework 6 and .NET 4.5.1. And get the error "unable to locate property" when I use the Where clause on a navigation property. The call is not even made to the Webapi2 Controller
If I leave out the where clause, the data is returned correctly.
The relevant part of the c# class:
public class NotificationRule {
public Guid NotificationRuleId { get; set; }
public virtual NotificationRuleSet NotificationRuleSet { get; set; }
}
The relevant part of the C# class in the navigational property NotificationRuleSet:
public class NotificationRuleSet{
public Guid NotificationRuleSetId { get; set; }
public virtual List<NotificationRule> NotificationRules { get; set; }
}
The relevant part of the C# Breeze controller:
public IQueryable<NotificationRuleSet> NotificationRuleSets()
{
return _contextProvider.Context.NotificationRuleSets;
}
public IQueryable<NotificationRule> NotificationRules()
{
return _contextProvider.Context.NotificationRules;
}
The relevant part of the Query (Typescript):
var query = breeze.EntityQuery.from("NotificationRules")
.where ("NotificationRuleSet.NotificationRuleSetId","==", this.NotificationRuleSetId)
.expand("NotificationRuleSet");
var Result = this.BreezeEntityManager
.executeQuery(query)
.then((data) => this.RefreshViewModelCallback(data))
.fail((data) => alert("Fail to retrieve data"));
If I leave the Where clause out, the data is transferred correctly as you can see in this Fiddler dump:
{
"$id": "1",
"$type": "Imp.Classes.NotificationRule, Imp",
"NotificationRuleId": "11111111-be1e-423c-ac5b-f2c689093aca",
"NotificationRuleSet": {
"$id": "2",
"$type": "Imp.Classes.NotificationRuleSet, Imp",
"NotificationRuleSetId": "11111111-1bd6-4520-9f69-381504b8e2b2",
"NotificationRules": [
{
"$ref": "1"
}
],
},
}
So I get an error that a property does not exists, but it seems to exists.
Using a Where on a non navigational property works fine.
I've read something about camelCasing but replacing NotificationRuleSet with notificationRuleSet gives the same error.
EDIT:
The solutions seems to be that NotificationRules in the Viewmodels query should start with a lowercase character, regardless wether the first character of the controllers method name is upper or lowercase .

camelCasing is most likely your issue provided both the entity and property do exist -
.where('notificationRuleSet.notificationRuleSetId', "==", this.NotificationRuleSetId)
Remember that when you are camelCasing your property names it is for the navigation property as well.

I thought I had an explanation after reviewing you interaction with PW Kad.
My guess was that the ACTUAL defaultResourceName for your NotificationRule type is "notificationRules".
Can you tell me what it is? The following expression will reveal it:
manager.metadataStore.getEntityType('NotificationRule').defaultResourceName;
Another question. You say it fails. What is the failure exception (check the payload of the response). Is it something like this?
$id: "1",
$type: "System.Web.Http.HttpError, System.Web.Http",
Message: "The query specified in the URI is not valid.",
ExceptionMessage: "A binary operator with incompatible types was detected. Found operand types 'Edm.Guid' and 'Edm.String' for operator kind 'Equal'.",
ExceptionType: "Microsoft.Data.OData.ODataException",
Here is what I was thinking. Most of the time, Breeze doesn't need to know the root type of a query when that query is sent to the server. It can simply wait for the query results and reason over the JSON to determine the type (or types) involved.
But the occasional query involves a filter comparison that is ambiguous in its data type. GUIDs are a good example. Unless breeze knows the query root type it can't know for sure if the "11111111-be1e-423c-ac5b-f2c689093aca" in "foo == '11111111-be1e-423c-ac5b-f2c689093aca'" should be a string or a GUID. A human would guess it's a GUID; Breeze is not so sure. You can be sure only if you know the datatype of the "foo" property.
Breeze will compose the query anyway. If it guesses string if produces a URL that looks like "...foo eq '11111111-be1e-423c-ac5b-f2c689093aca'..." and that will fail (for me anyway).
I thought this could be your issue.
I tried an experiment in DocCode that I thought would demonstrate it. I changed the endpoint name for an Order query to something that is NOT the Order type's defaultResourceName(which is "Orders").
As it happens, Web API doesn't care if the URL says 'orders' or 'Orders' so I can achieve my goal of confusing Breeze about the root type by pointing the query to "orders" and the query should still be routed by Web API to the proper controller GET method.
I was expecting that Breeze would compose the GUID query as a string and thus I could duplicate your issue. Here is my attempt
/*********************************************************
* Orders of Customers with Alfred's ID
* Customer is the related parent of Order
* CustomerID is a GUID
* Demonstrates "nested query", filtering on a related entity
* where the filter criteria is ambiguous (string or GUID)
* and only knowing the root query type (Order) can disambiguate.
* The 'defaultResourceName' for Order is "Orders", not "orders"
* so I expect this test to fail ... but it doesn't ...
* because Breeze disambiguated anyway.
*********************************************************/
test("orders of Customers w/ Alfred's ID (resource name is lowercased)", 2, function () {
var query = EntityQuery.from("orders")
.where("Customer.CustomerID", "==", testFns.wellKnownData.alfredsID)
.expand("Customer");
verifyQuery(newEm, query, "orders query", showOrdersToAlfred);
});
Unfortunately, the test passes!
This is the URL that Breeze sent to the server:
http://localhost:56337/breeze/Northwind/orders?$filter=Customer.CustomerID eq guid'785efa04-cbf2-4dd7-a7de-083ee17b6ad2'&$expand=Customer
DAMN Breeze (v.1.4.12) was too smart for me. It somehow figured out that my comparison value is a GUID ... despite not knowing the root type of the query.
That means I do not have an explanation for why, in your example, breeze.EntityQuery.from("notificationRules") works but breeze.EntityQuery.from("NotificationRules") does not.
Maybe I'll have another idea once you tell us the defaultResourceName AND show us the URLs that are generated (a) when it works and (b) when it does not work.

Related

Common fields on graphql interface type in react apollo with a graphene backend

I have a python graphene-django backend with an interface and two types, let's say
interface InterfaceType {
id: ID!
name: String!
}
type Type1 implements InterfaceType {
aField: String
}
type Type2 implements InterfaceType {
anotherField: String
}
I'm able to query this from my react-apollo frontend using inline fragments:
query {
interfaceQuery {
...on Type1 {
id
name
}
...on Type1 {
id
name
}
}
}
But from what I understand it should also be possible to query the common fields simply as
query {
interfaceQuery
id
name
}
}
When I try this, however, I get the error Cannot query field "id" on type "InterfaceType". Did you mean to use an inline fragment on "Type1" or "Type2"?
I'm using an IntrospectionFragmentMatcher.
Am I misunderstanding and this kind of simple access of common fields is not possible, or is it just not implemented in either graphene or apollo?
If you're seeing that error, it's coming from the server, not Apollo. However, there's nothing specific to either Apollo or Graphene that should prevent you from querying the interface fields without a fragment.
The error is thrown because whatever schema you're using literally doesn't have that field on the provided type. Maybe you updated your schema without restarting the service, or were mistaken about what fields were actually part of the interface -- it's hard to know with only pseudocode provided.

Access underlying DbContext (or run stored procedure) from Entity Framework POCO method

Is it possible to access the underlying DbContext (the DbContext that has populated this object/has this object in its cache/is tracking this object) from inside a model object, and if so, how?
The best answer I have found so far is this blog post which is five years old. Is it still the best solution available?
I’m using the latest version of Entity Framework if that matters.
Here's a sample to clarify my question:
I have a hierarchical tree. Let’s say it is categories that could have sub-categories. The model object would be something like this:
class Category
{
string CategoryId { get; set; }
string Name { get; set; }
virtual Category Parent { get; set; }
virtual ICollection<Category> Children { get; set; }
}
Now, if I want to access all descendants of a category (not just its immediate children) I can use a recursive query like this:
class Category
{
//...
IEnumerable<Category> Descendants
{
get
{
return Children.Union(Children.SelectMany(q => q.Descendants));
}
}
}
which works, but has bad performance (due to multiple database queries it needs to perform).
But suppose I have an optimized query that I can run to find descendent (maybe I store my primary key in a way that already contains path, or maybe I’m using SQL Server data type hierarchyid, etc.). How can I run such a query, which needs access to the whole table/database and not just the records available through model object’s navigational properties?
This can be either done by running a stored procedure/SQL command on the database, or a query like this:
class Category
{
//...
IEnumerable<Category> Descendants
{
get
{
// this won't work, because underlying DbContext is not available in this context!
return myDbContext.Categories.Where(q => q.CategoryId.StartsWith(this.CategoryId));
}
}
}
Is there a way at all to implement such a method?

Possible bug in breeze 1.4.14

I haven't tested this against the 1.4.16 release that came out a couple of weeks ago but there is nothing in the release notes about it.
The problem occurs with predicates where the value you are comparing is identical to the name of a property on any entity that breeze knows about. A simple test case is :
var query = breeze.EntityQuery.from('Items');
var pred = breeze.Predicate.create('name', breeze.FilterQueryOp.Contains, searchTerm);
query = query.where(pred);
Where searchTerm is equal to any string other than "name" this produces an oData query as below:
Items?$filter=(substringof(%27somevalue%27%2CName)%20eq%20true)
but if searchTerm = "name" then it produces the following query
Items?$filter=(substringof(Name%2CName)%20eq%20true)
Which istead of comparing the string 'name' against the property Name, it compares the property Name with itself.
I have not tested every operator but as far as I can tell it does not matter which you use you get the same behaviour.
You also get the same problem when querying navigation properties but it usually results in an invalid query. Below is a predicate for the same entity but against a navigation property tags that contains a collection of ItemTag entities that have a "Tag" property on them.
breeze.Predicate.create('tags', breeze.filterQueryOp.Any, 'tag', breeze.filterQueryOp.Contains, searchTerm)
It works fine for any searchTerm other than "tag" where it produces an oData request as below:
Items?$filter=Tags%2Fany(x1%3A%20substringof(%27somevalue%27%2Cx1%2FTag)%20eq%20true)
but if the searchTerm is "tag" then it requests:
Items?$filter=Tags%2Fany(x1%3A%20substringof(Tag%2Cx1%2FTag)%20eq%20true)
which produces an error of "Could not find a property named 'Tag' on type 'Item'" because the property Tag exists on the ItemTag entity.
In short breeze seems to infer that any search term that is identical to the name of a property it knows about, refers to that property rather than being a string literal value.
Has anyone else encountered this?
Is this a bug, or is there a way to explicitly tell breeze to interpret that value as a string literal and not a reference to a property?
I am not sure it is relevant as the server seems to be responding correctly to the requests and it is breeze that is creating incorrect requests but on the server side I am using Web API oData controllers with EF as ORM data layer.
Try
var pred = breeze.Predicate.create('name', breeze.FilterQueryOp.Contains,
{ value: searchTerm, isLiteral: true} );
This is described here ( under the explanation of the value parameter):
http://www.breezejs.com/sites/all/apidocs/classes/Predicate.html#method_create
if the value can be interpreted as a property expression it will be, otherwise it will be treated as a literal.
In most cases this works well, but you can also force the interpretation by making the value argument itself an object with a 'value' property and an 'isLiteral' property set to either true or false.
Breeze also tries to infer the dataType of any literal based on context, if this fails you can force this inference by making the value argument an object with a 'value' property and a 'dataType'property set
to one of the breeze.DataType enumeration instances.
The reason for this logic is to allow expressions where both sides of the expression are properties. For example to query for employees with the same first and last name you'd do this:
var q = EntityQuery.from("Employees")
.where("lastName", "==", "firstName");
whereas if you wanted employees with a lastName of 'firstName' you'd do this:
var q = EntityQuery.from("Employees")
.where("lastName", "startsWith", { value: "firstName", isLiteral: true })

Entity Framework TPH - Additional WHERE clause only for one subtype

Suppose I have a class Parent, with two subclasses, AChild and BChild. I have these mapped to a single table using Entity Framework 5.0.0 on .NET 4.5, using TPH.
public abstract class Parent {
public string Type { get; set; } // Column with this name in DB is discriminator.
public string Status { get; set; }
}
public class AChild : Parent {
// Other stuff.
}
public class BChild : Parent {
// Other stuff.
}
The code to configure the mapping:
class ParentConfiguration : EntityTypeConfiguration<Parent> {
Map((EntityMappingConfiguration<AChild> mapping) => mapping
.Requires("Type")
.HasValue("A"));
Map((EntityMappingConfiguration<BChild> mapping) => mapping
.Requires("Type")
.HasValue("B"));
}
I have a need to run a query that returns both AChild and BChild objects. However, it needs to filter ONLY the AChild rows by a second column, which in this example I will call Status.
Ideally I would want to do the following:
public IList<Parent> RunQuery() {
IQueryable<Parent> query =
this.context.Set<Parent>()
.Where((Parent parent) => !parent.Type.Equals("A") || parent.Status.Equals("Foo"))
.OrderBy((Parent parent) => parent.Number);
return query.ToList();
}
This doesn't work. It insisted on looking for a "Type1" column instead of just letting both the discriminator and a "Type" property be mapped to the same "Type" column.
I know of the "OfType" extension method that can be used to completely filter down to one type, but that's too broad a brush in this case.
I could possibly run multiple queries and combine the results, but the actual system I'm building is doing paging, so if I need to pull back 10 rows, it gets messy (and inefficient) to query since I'll either end up pulling back too many rows, or not pull back enough and have to run extra queries.
Does anyone have any other thoughts?
There are few problems. First of all you cannot have discriminator mapped as a property. That is the reason why it is looking for Type1 column - your Type property results in second column because the first one is already mapped to .NET types of your classes. The only way to filter derived types is through OfType.
The query you want to build will be probably quite complex because you need to query for all Bs and concatenate them with result of query for filtered As. It will most probably not allow you to concatenate instances of Bs with As so you will have to convert them back to parent type.

What are drawbacks of storing Guid as String in MongoDB?

An application persists Guid field in Mongo and it ends up being stored as BinData:
"_id" : new BinData(3, "WBAc3FDBDU+Zh/cBQFPc3Q==")
The advantage in this case is compactness, the disadvantage shows up when one needs to troubleshoot the application. Guids are passed via URLs, and constantly transforming them to BinData when going to Mongo console is a bit painful.
What are drawbacks of storing Guid as string in addition to increase in size? One advantage is ease of troubleshooting:
"_id" : "3c901cac-5b90-4a09-896c-00e4779a9199"
Here is a prototype of a persistent entity in C#:
class Thing
{
[BsonIgnore]
public Guid Id { get; set; }
[BsonId]
public string DontUseInAppMongoId
{
get { return Id.ToString(); }
set { Id = Guid.Parse(value); }
}
}
In addition to gregor's answer, using Guids will currently prevent the use of the new Aggregation Framework as it is represented as a binary type. Regardless, you can do what you are wanting in an easier way. This will let the mongodb bson library handle doing the conversions for you.
public class MyClass
{
[BsonRepresentation(BsonType.String)]
public Guid Id { get; set;}
}
The drawbacks are that mongodb is optimised to use BSON ObjectID's so it will be slightly less efficient to use strings as ObjectID's. Also if you want to use range based queries on string ObjectIDs then a lexicographic compare will be used which may give different results than you expect. Other than that you can use strings as ObjectIDs.
See Optimizing ObjectIDs
http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs