How to apply ODataQueryOptions for DTO to underlying EntitySet?How do I enumerate an enum in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I generate a random int number?Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element existHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?OData $expand, DTOs, and Entity Frameworkodata error - operator with incompatible types was detectedEF Code First Join Table Returning Null ObjectC# ODataQueryOptions with EF6 navigation property filters. System.ArgumentNullException : Value cannot be null. Parameter name: typeHow do I map an OData nested filter query against a DTO to another entity?
Who or what determines if a curse is valid or not?
Why teach C using scanf without talking about command line arguments?
What could make large expeditions ineffective for exploring territory full of dangers and valuable resources?
Is it possible to have a career in SciComp without contributing to arms research?
The most secure way to handle someone forgetting to verify their account?
Inside Out and Back to Front
How important are the Author's mood and feelings for writing a story?
How should I interpret a promising preprint that was never published in a peer-reviewed journal?
Wait or be waiting?
Is encryption still applied if you ignore the SSL certificate warning for self-signed certs?
Authorship dispute on a paper that came out of a final report of a course?
Making a Dataset that emulates `ls -tlra`?
Why does a tetrahedral molecule like methane have a dipole moment of zero?
When a ball on a rope swings in a circle, is there both centripetal force and tension force?
What is this green alien supposed to be on the American covers of the "Hitchhiker's Guide to the Galaxy"?
How can I help our ranger feel special about her beast companion?
Manager is asking me to eat breakfast from now on
Transcendental and non-transcendental god and objectivism
Company looks for long-term employees, but I know I won't be interested in staying long
Discontinuous Tube visualization
How many opportunity attacks can you make per turn before becoming exhausted?
Inscriptio Labyrinthica
Demographic consequences of closed loop reincarnation
Should I have one hand on the throttle during engine ignition?
How to apply ODataQueryOptions for DTO to underlying EntitySet?
How do I enumerate an enum in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I generate a random int number?Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element existHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?OData $expand, DTOs, and Entity Frameworkodata error - operator with incompatible types was detectedEF Code First Join Table Returning Null ObjectC# ODataQueryOptions with EF6 navigation property filters. System.ArgumentNullException : Value cannot be null. Parameter name: typeHow do I map an OData nested filter query against a DTO to another entity?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
There are 2 classes, Foo and Bar. There is a Bar object nested in a Foo object.
public class Foo
public Guid FooId get; set;
public string FooName get; set;
[ForeignKey("Bar")]
public Guid BarId get; set;
public virtual Bar Bar get; set;
public class Bar
public Guid BarId get; set;
public string BarName get; set;
public class FooBarContext : DbContext
public DbSet<Foo> Foos get; set;
public DbSet<Bar> Bars get; set;
public class FooDTO
public Guid FooId get; set;
public string FooName get; set;
public Guid BarId get; set;
public string BarName get; set;
My question is: can I somehow translate the OData query for FooDTO to OData query for Foo, such that it can be applied to the Foos DbSet?
For example, I'd like to query by BarName, which is ultimately from the nested Bar object.
GET /Foos?$filter=BarName eq 'Bar2'
And here is the controller and action to process the query
public class FoosController
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
// translate filter FooDTO.BarName to filter Foo.Bar.Name
// ODataQueryOptions<Foo> fooQueryOptions = ....
using (var context = new FooBarContext())
return fooQueryOptions.ApplyTo(context.Foos);
Thank you.
c# entity-framework asp.net-web-api odata
add a comment |
There are 2 classes, Foo and Bar. There is a Bar object nested in a Foo object.
public class Foo
public Guid FooId get; set;
public string FooName get; set;
[ForeignKey("Bar")]
public Guid BarId get; set;
public virtual Bar Bar get; set;
public class Bar
public Guid BarId get; set;
public string BarName get; set;
public class FooBarContext : DbContext
public DbSet<Foo> Foos get; set;
public DbSet<Bar> Bars get; set;
public class FooDTO
public Guid FooId get; set;
public string FooName get; set;
public Guid BarId get; set;
public string BarName get; set;
My question is: can I somehow translate the OData query for FooDTO to OData query for Foo, such that it can be applied to the Foos DbSet?
For example, I'd like to query by BarName, which is ultimately from the nested Bar object.
GET /Foos?$filter=BarName eq 'Bar2'
And here is the controller and action to process the query
public class FoosController
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
// translate filter FooDTO.BarName to filter Foo.Bar.Name
// ODataQueryOptions<Foo> fooQueryOptions = ....
using (var context = new FooBarContext())
return fooQueryOptions.ApplyTo(context.Foos);
Thank you.
c# entity-framework asp.net-web-api odata
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04
add a comment |
There are 2 classes, Foo and Bar. There is a Bar object nested in a Foo object.
public class Foo
public Guid FooId get; set;
public string FooName get; set;
[ForeignKey("Bar")]
public Guid BarId get; set;
public virtual Bar Bar get; set;
public class Bar
public Guid BarId get; set;
public string BarName get; set;
public class FooBarContext : DbContext
public DbSet<Foo> Foos get; set;
public DbSet<Bar> Bars get; set;
public class FooDTO
public Guid FooId get; set;
public string FooName get; set;
public Guid BarId get; set;
public string BarName get; set;
My question is: can I somehow translate the OData query for FooDTO to OData query for Foo, such that it can be applied to the Foos DbSet?
For example, I'd like to query by BarName, which is ultimately from the nested Bar object.
GET /Foos?$filter=BarName eq 'Bar2'
And here is the controller and action to process the query
public class FoosController
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
// translate filter FooDTO.BarName to filter Foo.Bar.Name
// ODataQueryOptions<Foo> fooQueryOptions = ....
using (var context = new FooBarContext())
return fooQueryOptions.ApplyTo(context.Foos);
Thank you.
c# entity-framework asp.net-web-api odata
There are 2 classes, Foo and Bar. There is a Bar object nested in a Foo object.
public class Foo
public Guid FooId get; set;
public string FooName get; set;
[ForeignKey("Bar")]
public Guid BarId get; set;
public virtual Bar Bar get; set;
public class Bar
public Guid BarId get; set;
public string BarName get; set;
public class FooBarContext : DbContext
public DbSet<Foo> Foos get; set;
public DbSet<Bar> Bars get; set;
public class FooDTO
public Guid FooId get; set;
public string FooName get; set;
public Guid BarId get; set;
public string BarName get; set;
My question is: can I somehow translate the OData query for FooDTO to OData query for Foo, such that it can be applied to the Foos DbSet?
For example, I'd like to query by BarName, which is ultimately from the nested Bar object.
GET /Foos?$filter=BarName eq 'Bar2'
And here is the controller and action to process the query
public class FoosController
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
// translate filter FooDTO.BarName to filter Foo.Bar.Name
// ODataQueryOptions<Foo> fooQueryOptions = ....
using (var context = new FooBarContext())
return fooQueryOptions.ApplyTo(context.Foos);
Thank you.
c# entity-framework asp.net-web-api odata
c# entity-framework asp.net-web-api odata
asked Dec 15 '15 at 9:09
cltsangcltsang
1081 silver badge8 bronze badges
1081 silver badge8 bronze badges
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04
add a comment |
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04
add a comment |
1 Answer
1
active
oldest
votes
First Install the OData packages to your Web API project
Install-Package Microsoft.AspNet.OData -Version 7.1.0
Configure the OData endpoint in WebApiConfig.cs by Add the following using statements
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
And following code to the Register method
public static void Register(HttpConfiguration config)
config.MapHttpAttributeRoutes();
// New code start
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Foo>("Foos");
builder.EntitySet<Bar>("Bars");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.EnableDependencyInjection();
// New code end
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/id",
defaults: new id = RouteParameter.Optional
);
Updated for mapping: In your controller
[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
using (var context = new FooBarContext())
return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
BarId = f.BarId,
BarName = f.Bar.BarName,
FooId = f.FooId,
FooName = f.FooName
));
For more check Create an OData v4 Endpoint Using ASP.NET Web API,
Also Supercharging your Web APIs with OData and ASP.NET Core (For .Net core but it could help)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34285036%2fhow-to-apply-odataqueryoptions-for-dto-to-underlying-entityset%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
First Install the OData packages to your Web API project
Install-Package Microsoft.AspNet.OData -Version 7.1.0
Configure the OData endpoint in WebApiConfig.cs by Add the following using statements
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
And following code to the Register method
public static void Register(HttpConfiguration config)
config.MapHttpAttributeRoutes();
// New code start
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Foo>("Foos");
builder.EntitySet<Bar>("Bars");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.EnableDependencyInjection();
// New code end
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/id",
defaults: new id = RouteParameter.Optional
);
Updated for mapping: In your controller
[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
using (var context = new FooBarContext())
return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
BarId = f.BarId,
BarName = f.Bar.BarName,
FooId = f.FooId,
FooName = f.FooName
));
For more check Create an OData v4 Endpoint Using ASP.NET Web API,
Also Supercharging your Web APIs with OData and ASP.NET Core (For .Net core but it could help)
add a comment |
First Install the OData packages to your Web API project
Install-Package Microsoft.AspNet.OData -Version 7.1.0
Configure the OData endpoint in WebApiConfig.cs by Add the following using statements
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
And following code to the Register method
public static void Register(HttpConfiguration config)
config.MapHttpAttributeRoutes();
// New code start
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Foo>("Foos");
builder.EntitySet<Bar>("Bars");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.EnableDependencyInjection();
// New code end
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/id",
defaults: new id = RouteParameter.Optional
);
Updated for mapping: In your controller
[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
using (var context = new FooBarContext())
return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
BarId = f.BarId,
BarName = f.Bar.BarName,
FooId = f.FooId,
FooName = f.FooName
));
For more check Create an OData v4 Endpoint Using ASP.NET Web API,
Also Supercharging your Web APIs with OData and ASP.NET Core (For .Net core but it could help)
add a comment |
First Install the OData packages to your Web API project
Install-Package Microsoft.AspNet.OData -Version 7.1.0
Configure the OData endpoint in WebApiConfig.cs by Add the following using statements
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
And following code to the Register method
public static void Register(HttpConfiguration config)
config.MapHttpAttributeRoutes();
// New code start
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Foo>("Foos");
builder.EntitySet<Bar>("Bars");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.EnableDependencyInjection();
// New code end
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/id",
defaults: new id = RouteParameter.Optional
);
Updated for mapping: In your controller
[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
using (var context = new FooBarContext())
return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
BarId = f.BarId,
BarName = f.Bar.BarName,
FooId = f.FooId,
FooName = f.FooName
));
For more check Create an OData v4 Endpoint Using ASP.NET Web API,
Also Supercharging your Web APIs with OData and ASP.NET Core (For .Net core but it could help)
First Install the OData packages to your Web API project
Install-Package Microsoft.AspNet.OData -Version 7.1.0
Configure the OData endpoint in WebApiConfig.cs by Add the following using statements
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
And following code to the Register method
public static void Register(HttpConfiguration config)
config.MapHttpAttributeRoutes();
// New code start
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Foo>("Foos");
builder.EntitySet<Bar>("Bars");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
config.EnableDependencyInjection();
// New code end
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/id",
defaults: new id = RouteParameter.Optional
);
Updated for mapping: In your controller
[EnableQuery()] // Enables clients to modify the query, by using query options such as $filter, $sort, and $page
public async Task<IHttpActionResult> GetFoos(ODataQueryOptions<FooDTO> queryOptions)
using (var context = new FooBarContext())
return queryOptions.ApplyTo(context.Foos.AsQueryable().Select(f => new FooDTO
BarId = f.BarId,
BarName = f.Bar.BarName,
FooId = f.FooId,
FooName = f.FooName
));
For more check Create an OData v4 Endpoint Using ASP.NET Web API,
Also Supercharging your Web APIs with OData and ASP.NET Core (For .Net core but it could help)
edited Mar 28 at 10:26
answered Mar 26 at 11:15
ElasticCodeElasticCode
3,4012 gold badges13 silver badges25 bronze badges
3,4012 gold badges13 silver badges25 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34285036%2fhow-to-apply-odataqueryoptions-for-dto-to-underlying-entityset%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Did you solve your problem?
– tymtam
May 17 '16 at 1:59
@Tymek Sorry for the late reply. I end up implementing my own solution, ditching OData. But if you'd like to use OData, as far as I know the only 2 options are AutoMapper, and parsing and constructing the query yourself. To parse OData query, please refer to this article ben-morris.com/…
– cltsang
May 25 '16 at 4:04