In my edmx model are 2 related tables: Challenge and ChallengeNote (has FK back to ChallengeID)
I can do this in breeze all day long
var qry = dataservice.getQuery("Challenges");
However, this fails every time:
var qry = dataservice.getQuery("Challenges").expand("ChallengeNotes");
The searchFailed is called and is the only error information in the console.
return dataservice.execute(qry.inlineCount(true))
.then(seachSucceeded)
.fail(searchFailed);
Does Breeze support relational data like this?
Does one need to write some custom code to support?
What am I missing?
Here's related answered question, but I was already following (unless I missed something) the answer's solution (and why I have the 2 context.Configuration settings in my ContextProvider).
breezejs-error-when-loading-an-entity-with-related-data
Here's another similar question that's been unanswered breeze-expand-query-fails-with-object-object-has-no-method-getproperty
Here's my provider code (want to use the BeforeSaveEntity override further on in the project):
public class ModelProvider : EFContextProvider<ModelEntities>
{
public ModelProvider()
: base()
{
this.Context.Configuration.LazyLoadingEnabled = false;
this.Context.Configuration.ProxyCreationEnabled = false;
}
}
Here's my controller code:
[BreezeController]
public class DataController : ApiController
{
readonly ModelProvider _contextProvider = new ModelProvider();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
[HttpGet]
public IQueryable<Challenge> Challenges()
{
return _contextProvider.Context.Challenges.Include(x => x.ChallengeNotes);
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
[HttpGet]
public IQueryable<ChallengeNote> ChallengeNotes()
{
return _contextProvider.Context.ChallengeNotes;
}
}
When I browse to the URL, it's including the related entity:
http://localhost:53644/breeze/data/Challenges?$filter=Active%20eq%20true&$top=10&$expand=ChallengeNotes&$inlinecount=allpages
Here is the data coming from the Controller
At this point all things, imo, are pointing to Breeze configuration on either the Server or Client.
TIA
Breeze absolutely does support this, but you do need to make sure that your Entity Framework model is set up correctly. Take a look at the DocCode sample in the Breeze zip for a number of examples of using both expand (client side) or EF include (server side) clauses.
One guess about your problem is that you are using the Breeze camelCasing naming convention and therefore your "expand" clause should be
var qry = dataservice.getQuery("Challenges").expand("challengeNotes");
i.e. "challengeNotes" (note the casing) is the name of the client side property that corresponds to a server side property of "ChallengeNotes". To clarify, "expand" clauses take the names of client side "properties" as parameters and property names are what are transformed as a result of the Breeze.NamingConvention.
In contrast, a query resource name i.e. "Challenges" in your example is the name of the server side resource ( as a result of marking your "Challenges" method with the [HttpGet] annotation. This name is NOT affected by the NamingConvention.
Side notes: Your example has both an expand and an Include clause. Either of these is sufficient all by itself. You do not need both. In general you can either include an "expand" clause in your client side query OR have an Entity Framework "Include" clause on the server. The advantage of the first is that you can control the expand on the client, the advantage of the second is that you can insure that every query for a specified resource always fetches some related entities.
Hope this helps!
Related
I'm investigating Web Api in ASP.NET vNext using the daily builds. In a web api 2x project, I use HttpParameterBinding and ParameterBindingAttribute in some situations (see http://bit.ly/1sxAxdk); however, I can't seem to find either in vNext. Do/will these classes exist? If not, what are my alternatives?
Edit (1-22-15):
I want to be able to serialize a complex JS object to a JSON string, put the JSON string in a hidden form field (say name="data"), submit the form, and then bind my parameter to that JSON object on the server. This will never be done by a human, but rather by a machine. I also want this very same mechanism to work if the JSON is sent directly in the request body instead of form data. I also need this to work for several different types of objects.
I've been able to accomplish this scenario in Web Api 2.2 in a few different ways, including a custom ModelBinder; however, I remember reading an MSFT blog post that suggested to use a ModelBinder for query string binding, formatters for request body, and HttpParameterBinding for more general scenarios. Is it okay to read the request body in a ModelBinder ASP.NET 5, or is there a better mechanism for that? If so, then case closed and I will port my ModelBinder with a few minor changes.
I'm not sure that IInputFormatter will work for me in this case either.
Here are two rough approaches
Approach 1:
A quick and dirty approach would be to start with a Dto model
public class Dto
{
public Serializable Result { get; set; }
public Serializable FromForm
{
get { return Result; }
set { Result = value; }
}
[FromBody]
public Serializable FromBody
{
get { return Result; }
set { Result = value; }
}
}
public class Serializable
{
}
And an action method
public IActionResult DoSomething(Dto dto)
{
// Do something with Dto.Result
}
Then write a custom model binder for Serializable, that just works with Request.Form this way you never actually read the body yourself, and Form only reads it if it of type Form.
The down side of this is that ApiExplorer will not provide correct details (but I think since this is none-standard you are going to be in trouble here anyways).
Approach 2
You can alternatively just use the code from BodyModelBinder and create a custom binder for Serializable type above, that first tries to get it from the Form, and if it fails tries to get it from the Body. The Dto class in that case is not necessary.
Here is some pseudo code
if (inputType is yourtype)
{
if (request.Form["yourkey"] != null)
{
Use Json.Net to deserialize your object type
}
else
{
fall back to BodyModelBinder code
}
}
With this approach you can make it generic, and ApiExplorer will say the way to bind the type is unknown/custom (we haven't decided on the term yet :) )
Note:
Instead of registering the model binder you can use the [ModelBinder(typeof(customBinder))] attribute to apply it sparingly.
Here is a link to the BodyModelBinder code.
There is a new [FromHeader] attribute that allows you to bind directly to http header values if that is what you need.
https://github.com/aspnet/Mvc/issues/1671
https://github.com/aspnet/Mvc/search?utf8=%E2%9C%93&q=fromheader
I'd like to configure a route that always returns a single entity.
The controller looks like:
class StatsController: ODataController {
public Stats Get() {
return new Stats();
}
}
The url to access it should be: GET ~/service-prefix/stats
All the options I've seen involve having to return IQueryable, or when returning a single entity, passing in a key in a form of ~/service-prefix/EntitySet(1)
Is there a way to achieve the above without having to return an IQueriable?
By default any action of the following forms should be reachable for your scenario:
Example:
public Stat Get([FromODataUri] int key) { }
or
public Stat Get#your-entity-name#([FromODataUri] int key) { }
To access a single object without needing to have an entityset, odata v4 introduces the concept of singletons.
From OData v4 spec:
A singleton allows addressing a single entity directly from the entity container without having to know its key, and without requiring an entity set.
More info:
Use Singleton to define your special entity
ODataLib for OData v4: Singletons and Containment
I believe Singleton could meet your requirement, but it is not implemented in WebApi. Fortunately, there is another option: unbound function. Just follow this sample: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/.
There is a method in ProductsController:
[HttpGet]
[ODataRoute("GetSalesTaxRate(state={state})")]
public IHttpActionResult GetSalesTaxRate([FromODataUri] string state)
{
return Ok(GetRate(state));
}
It is requested through this URL: ~/service-prefix/GetSalesTaxReate(state='WA') and is very close to your scenario. The only thing you need to do is to remove the parameter of the function:
[HttpGet]
[ODataRoute("GetStats()")]
public IHttpActionResult GetStats()
{
return Ok(new Stats());
}
Now you can request ~/sevice-prefix/GetStats().
Following code converts the ViewModel query to model and then converts the returned result back to ViewModel as PageResult. All this works fine but when I try to use include as part of my default query(or even with the latest version as part of querycontext) then OData formatter plays funny and doesn't include child elements. I have debugged and confirmed that it actually contains child elements. This only happens for controllers that I extended from ODataController(so basically for the ones that are extended from ApiController all works fine but i need results in OData format).
Please note that I have also tried with the latest nightly build(Microsoft.Data.OData 5.5.0.0) and still it doesn't work for me.
Any help would highly be appreciated.
public class ProductsController : ODataController
{
APPContext context = new APPContext();
public PageResult<ProductViewModel> Get(ODataQueryOptions QueryOptions)
{
EdmModel model = new EdmModel();
ODataQueryContext queryContext = new ODataQueryContext(model.GetEdmModel(), typeof(Product));
var mappedQuery = new ODataQueryOptions(queryContext, QueryOptions.Request);
var results = new List<ProductViewModel>();
foreach (var result in mappedQuery.ApplyTo(this.context.Serials.Include("Status").Include("Category")))
{
AutoMapper.Mapper.CreateMap(result.GetType(), typeof(ProductViewModel));
results.Add(AutoMapper.Mapper.Map<ProductViewModel>(result));
}
PageResult<ProductViewModel> pr = new PageResult<ProductViewModel>(results.AsEnumerable<ProductViewModel>(), mappedQuery.Request.GetNextPageLink(), mappedQuery.Request.GetInlineCount());
return pr;
}
}
In OData related entities are represented as navigation links. So, if you have a customers feed, the related orders for each customer will not be part of the customers feed. Instead, they would be represented as navigation links. You can explicitly tell the OData service to expand the related entities using the $expand query option. So, if you want the related orders for each customer to be expanded, you should ask for the url ~/Customers?$expand=Orders.
I am working on asp.net MVC 3 project. I am using EF 4.1 code first approach. I have entity class called disputes. It maps to a table in database name tblDisptes. It has three properties names Lastviewedby, Lastupdatedby, LastRespondedBy ... all three integers. I have created a viewmodel 'disputeviewmodel' with three more properties Lastviewedbyname, Lastupdatedbyname, LastRespondedByname and a property named dispute. Now my repository function returns list of disputes. how to convert this list to List of disputeviewmodel so that these three properties are filled with the names ?
Please suggest.
Your view model doesn't really need a property named dispute. A view model should not reference your domain models.
As far as the mapping is concerned one possibility is to manually do it but that could quickly become cumbersome with more complex models:
public ActionResult Foo()
{
IEnumerable<disputes> disputes = ... fetch from repo
IEnumerable<disputeviewmodel> disputeViewModels = disputes.Select(x => new disputeviewmodel
{
Lastviewedbyname = x.Lastviewedby,
Lastupdatedbyname = x.Lastupdatedby,
LastRespondedByname = x.LastRespondedBy
});
return View(disputeViewModels);
}
So a better approach would be to use AutoMapper:
public ActionResult Foo()
{
IEnumerable<disputes> disputes = ... fetch from repo
IEnumerable<disputeviewmodel> disputeViewModels = Mapper.Map<IEnumerable<disputes>, IEnumerable<disputeviewmodel>>(disputes);
return View(disputeViewModels);
}
Why your Dispute doesn't look like that?
class Dispute
{
public User LastViewedBy;
public User Lastupdatedbyname
public User LastRespondedByname
}
That's how it should look. Then problem solved. When you query for Disputes you already have Users (with there usernames) ready.
I'm using logical delete in my system and would like to have every call made to the database filtered automatically.
Let say that I'm loading data from the database in the following way :
product.Regions
How could I filter every request made since Regions is an EntitySet<Region> and not a custom method thus not allowing me to add isDeleted = 0
So far I found AssociateWith but I'd hate to have to write a line of code for each Table -> Association of the current project...
I'm looking into either building generic lambda Expressions or.. something else?
You could create an extension method that implements your filter and use that as your convention.
public static class RegionQuery
{
public static IQueryable<Region> GetAll(this IQueryable<Region> query, bool excludeDeleted=true)
{
if (excludeDeleted)
return query.Regions.Where(r => !r.isDeleted);
return query.Regions;
}
}
So whenever you want to query for regions you can make the following call to get only the live regions still providing an opportunity to get at the deleted ones as well.
context.Regions.GetAll();
It my be a little wonky for access the Products property, but still doable. Only issue is you would have to conform to the convention. Or extend the containing class.
someProduct.Regions.GetAll();
I hope that helps. That is what I ended up settling on because I haven't been able to find a solution to this either outside of creating more indirection. Let me know if you or anyone else comes up with a solution to this one. I'm very interested.
It looks to me like you're using a relationship between your Product and Region classes. If so, then somewhere, (the .dbml file for auto-generated LINQ-to-SQL), there exists a mapping that defines the relationship:
[Table(Name = "Product")]
public partial class Product
{
...
private EntitySet<Region> _Regions;
[Association(Storage = "_Regions")]
public EntitySet<Region> Regions
{
get { return this._Regions; }
set { this._Regions.Assign(value); }
}
...
}
You could put some logic in the accessor here, for example:
public IEnumerable<Region> Regions
{
get { return this._Regions.Where(r => !r.isDeleted); }
set { this._Regions.Assign(value); }
}
This way every access through product.Regions will return your filtered Enumerable.