I am having issues in trying to query my Azure DocumentDb storage account when attempting to retrieve a single record. This is my WebAPI code:
// Controller...
public AccountController : ApiController {
// other actions...
[HttpGet]
[Route("Profile")]
public HttpResponseMessage Profile()
{
var userId = User.Identity.GetUserId();
var rep = new DocumentRepository<UserDetail>();
var profile = rep.FindById(userId);
if (profile == null)
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Profile not found");
return Request.CreateResponse(HttpStatusCode.OK, profile);
}
}
// Repository
public class DocumentRepository<TEntity> : IDocumentRepository<TEntity> where TEntity : IIdentifiableEntity
{
private static DocumentClient _client;
private static string _databaseName;
private static string _documentsLink;
private static string _selfLink;
public DocumentRepository()
{
_client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentDbEndpointUrl"]), ConfigurationManager.AppSettings["DocumentDbAuthKey"]);
_databaseName = ConfigurationManager.AppSettings["DocumentDbDatabaseName"];
var _database = ReadOrCreateDatabase();
var collection = InitialiseCollection(_database.SelfLink, EntityName);
_documentsLink = collection.DocumentsLink;
_selfLink = collection.SelfLink;
}
// other methods...
public TEntity FindById(string id)
{
return _client.CreateDocumentQuery<TEntity>(_documentsLink).SingleOrDefault(u => u.Id.ToString() == id);
}
}
It is this FindById method which causes the following issue:
An exception of type 'Microsoft.Azure.Documents.Linq.DocumentQueryException' occurred in Microsoft.Azure.Documents.Client.dll but was not handled in user code
Additional information: Query expression is invalid, expression return type
Foo.Models.DocumentDbEntities.UserDetail is unsupported. Query must evaluate to IEnumerable.
I don't understand what this error means, or how I fix it. I don't wish to return an IEnumerable or any descendant class as this method will return either 0 or 1 records. It works if I remove the SingleOrDefault clause, and change the return type to an IQueryable, however this is not what I want.
SingleOrDefault() is not supported, yet in the LINQ provider.
Change this to .Where(u => u.Id.ToString() == id).AsEnumberable().FirstOrDefault();
I can't say why Ryan's syntax stopped working for you, but you should be able to work around it without the extra performance hit by using a CreateDocumentQuery<>() overload with an explicitly-defined query string instead of using .Where():
string query = string.Format("SELECT * FROM docs WHERE docs.id = \"{0}\"", id);
return _client.CreateDocumentQuery<TEntity>(DocumentsLink, query).AsEnumerable().FirstOrDefault();
You might need to play with the query a little, but something of that form ought to work.
Related
I'm interested in capturing the name of the method that initiated an Entity Framework query. I will be using this functionality in both Entity Framework 6 and Entity Framework Core
Consider the following class:
namespace MyCompany.MyApp
{
public class MyDataClass
{
// ... snip ...
public Person GetPerson(long id)
{
return _dbContext
.Person
.FirstOrDefault(p => p.Id == id);
}
}
}
And the following interceptor:
public class EFCommandInterceptor : IDbCommandInterceptor
{
// ... snip other interface methods ...
public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
var callingMehtod = GetCallingMethod() // <--- I'd like this to return the string "MyCompany.MyApp.MyDataClass.GetPerson"
}
}
Is there any way to determine what method initiated the query that resulted in the interceptor being called?
As I'm going to be using this functionality for tracing and performance analysis, I can't send and record the entire Environment.StackTrace for every query running through the system.
I also considered using the StackTrace class in conjunction with stackTrace.GetFrames() to try to analyze the call stack to find the actual method that initiated the query, but it's not clear how to do this reliably without relying on some kind of namespace convention that universally identifies a data access class.
Another approach that would be acceptable might look something like:
namespace MyCompany.MyApp
{
public class MyDataClass
{
// ... snip ...
public Person GetPerson(long id)
{
return _dbContext
.Person
.WithExtraInterceptorContext(new { CallingMethod = "MyCompany.MyApp.MyDataClass.GetPerson"}) // <--- Can something like this be done?
.FirstOrDefault(p => p.Id == id);
}
}
}
The intention with the above example would be able to later retrieve the extra context via the DbCommandInterceptionContext inside IDbCommandInterceptor
Ultimately, the problem I'm trying to solve is to get the fully qualified name of the method that initiated a query without having a full call stack.
With EF Core you can use TagWith
var result = db.Albums
.TagWith(MethodBase.GetCurrentMethod().Name)
.ToList();
You could simply register the information before running the query, something like:
public Person GetPerson(long id)
{
EfDebug.SetCurrentMethodName();
return _dbContext
.Person
.WithExtraInterceptorContext(new { CallingMethod = "MyCompany.MyApp.MyDataClass.GetPerson"}) // <--- Can something like this be done?
.FirstOrDefault(p => p.Id == id);
}
. . .
static class EfDebugExtensions
{
public static AsyncLocal<string> CurrentMethodName = new AsyncLocal<string>();
public static void SetCurrentMethodName([CallerMemberName] string caller = "")
{
CurrentMethodName.Value = caller;
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source,[CallerMemberName] string caller = "")
{
CurrentMethodName.Value = caller;
var rv = Enumerable.FirstOrDefault(source);
return rv;
}
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source, [CallerMemberName] string caller = "")
{
CurrentMethodName.Value = caller;
var rv = Enumerable.ToList(source);
return rv;
}
}
I have this method:
public IQueryable<T> List(HttpRequestMessage request)
{
var queryString = request.GetQueryNameValuePairs();
var models = _service.List();
foreach(var item in queryString)
models = models.Where(m => m.GetType().GetProperty(item.Key).GetValue(m).ToString().Contains(item.Value));
return models;
}
And when I run it I get this error:
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.
Which I have been unable to fix. Does anyone know how to fix it or can show me where I can find out?
I fixed this by using System.Linq.Dynamic as suggested and I was able to do this:
public class DataProvider<T> where T : class
{
private readonly IService<T> _service;
public DataProvider(IService<T> service) => _service = service;
public IQueryable<T> List(HttpRequestMessage request)
{
var queryString = request.GetQueryNameValuePairs();
var models = _service.List();
foreach (var item in queryString)
{
var query = $"{ item.Key }.ToString().Contains(\"{ item.Value }\")";
models = models.Where(query);
}
return models;
}
}
Which allowed me to use Generics and fix my issue :)
How do I query a SingleResult object in a ASP.NET based server? Please help with the below code.
public class UserController : TableController<User>
{
...
public Task DeleteUser(string id)
{
SingleResult<User> user = Lookup(id);
// I can drill down into user via the debugger and see the data
// I'm looking for. But I don't know how to translate what I see
// in the debugger to a .Net call.
// This is what I see in the debugger:
// new System.Linq.SystemCore_EnumerableDebugView
// <AlertMeService.DataObjects.User>(result.Queryable).Items[0].GroupNm
// which equals "fooGrp"
// The below call doesn't work
// string GroupNm = user.GroupNm;
// I need GroupNm from the object to send a group notification
PostNotification(user.GroupNm, ...);
return DeleteAsync(id);
}
...
Any help is greatly appreciated.
SingleResult returns an IQueryable, so use the Linq Single or SingleOrDefault methods to execute the query and get the result.
Single will throw an exception if 0, 2 or more values are returned, and SingleOrDefault will allow either 0 or 1 value and will throw if 2 or more than values are returned. If you want multiple values then use First/FirstOrDefault or Last/LastOrDefault, or some other terminal Linq method, as appropriate
SingleResult<User> userQuery = Lookup(id);
User user = userQuery.SingleOrDefault();
if( user == null ) {
}
else {
}
According to your description, I have checked the SingleResult class:
public sealed class SingleResult<T> : SingleResult
{
//
// Summary:
// Initializes a new instance of the System.Web.Http.SingleResult`1 class.
//
// Parameters:
// queryable:
// The System.Linq.IQueryable`1 containing zero or one entities.
public SingleResult(IQueryable<T> queryable);
//
// Summary:
// The System.Linq.IQueryable`1 containing zero or one entities.
public IQueryable<T> Queryable { get; }
}
Per my understanding, you could modify your DeleteUser method as follows:
public Task DeleteUser(string id)
{
SingleResult<User> result = Lookup(id);
var user=result.Queryable.SingleOrDefault();
if(user!=null)
{
//I need GroupNm from the object to send a group notification
PostNotification(user.GroupNm, ...);
return DeleteAsync(id);
}
return Task.FromException($"the specific user with userid:{id} is not found.");
}
I am new with c# controllers and I am trying to join two entities with a LINQ query. But I am getting a 'missing a cast' error message as shown below that I don't understand and it does not help me to correct the error.
The controller looks like:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public SoonDueReportsController_simple Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
This type of controller I have used with success for single entities (tables from an sql db) to display static data in a kendo grid. But I fail when I try to join two tables as shown above. If someone could help me with this problem I'd appreciate it very much.
Regards, Manu
You select a collection of anonymous objects
select new
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
And want the method to return a instance of certain type. C# is the strongly typed language without type inference, which means you have to specifically create objects of a certain type or interface if you want to return them.
Also, you are have the controller type itself to be returned from the Get method. This makes no sense. I actually do not know what you want to do but may be this would work:
public class SoonDueReportsController_simple : BaseODataController
{
public SoonDueReportsController_simple(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
[Queryable(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<SomeModel> Get()
{
var falligkeiten = UnitOfWork.GetAll<Fälligkeiten>();
var betriebe = UnitOfWork.GetAll<Betriebe>();
var query = (from betrieb in betriebe.AsQueryable()
join fallig in falligkeiten.AsQueryable()
on betrieb.ID equals
fallig.Betrieb_ID
where fallig.Fälligkeit_Erledigt_Datum == null
&& betrieb.Aktiv == true
select new SomeModel
{
BetriebId = betrieb.ID,
FalligkeitObject = fallig.Fälligkeit_Objekt
});
return query;
}
}
public class SomeModel
{
public int BetriebId { get; set; }
public string FalligkeitObject { get; set; }
}
Please bear in mind that there are no such things as "C# controllers". You are working with OData, so I would recommend you to look at some OData resources, there are plenty of examples out there.
And one last thing, don't get me wrong, but it does not help giving properties, types and other identifiers German names. People would have hard time trying to understand your code.
The exception explains to you the problem exactly. You're wanting to return a type of 'SoonDueReportsController_simple' and yet you are returning a Queryable where a' is your new { ..., ... } object.
I like the suggestion given to make a strong typed object and fill it but you can also return a dynamic type.
This code works to explain:
private dynamic Get() => new { Name = "SomeName", Age = 31 };
private void TestGet()
{
var obj = Get();
var name = obj.Name;
var age = obj.Age;
}
I know this question has already been asked but I couldn't find an answer that satisfied me. What I am trying to do is to retrieve a particular DbSet<T> based on its type's name.
I have the following :
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyDllAssemblyName")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyCallingAssemblyName")]
class MyDbContext : DbContext {
public DbSet<ModelA> A { get; set; }
public DbSet<ModelB> B { get; set; }
public dynamic GetByName_SwitchTest(string name) {
switch (name) {
case "A": return A;
case "B": return B;
}
}
public dynamic GetByName_ReflectionTest(string fullname)
{
Type targetType = Type.GetType(fullname);
var model = GetType()
.GetRuntimeProperties()
.Where(o =>
o.PropertyType.IsGenericType &&
o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
o.PropertyType.GenericTypeArguments.Contains(targetType))
.FirstOrDefault();
if (null != model)
return model.GetValue(this);
return null;
}
}
I have no trouble getting the type itself whether it is via a simple switch or reflection. I need however to return the type as a dynamic since I do not know what DbSet type it will be.
Then somewhere else in the same assembly, I use it this way :
// MyDbContext MyDbContextInstance..
var model = MyDbContextInstance.GetByName_SwitchTest("A");
var record1 = model.FirstOrDefault(); // It crashes here with RunTimeBinderException
At this point model contains an instance of a InternalDbSet<ModelA> type. From there, any use I do with the model object I get a RunTimeBinderException :
'Microsoft.Data.Entity.Internal.InternalDbSet' does not contain a definition for 'FirstOrDefault'
Investigating on the web, I found a blog post explaining that (dixit his blog) :
the reason the call to FirstOrDefault() fails is that the type
information of model is not available at runtime. The reason it's not
available is because anonymous types are not public. When the method
is returning an instance of that anonymous type, it's returning a
System.Object which references an instance of an anonymous type - a
type whose info isn't available to the main program.
And then he points that a solution :
The solution is actually quite simple. All we have to do is open up
AssemplyInfo.cs of the ClassLibrary1 project and add the following
line to it: [assembly:InternalsVisibleTo("assembly-name")]
I did try this solution on my code but it doesn't work. For info I have an asp.net 5 solution with two assemblies running on dnx dotnet46. An app and a dll containing all my models and DbContext. All the concerned calls I do are located on the dll though.
Does this solution have any chance to work ?
Am I missing something ?
Any pointers would be greatly appreciated ?
Thanks in advance
[EDIT]
I have tried to return IQueryable<dynamic> rather than dynamic and I could do the basic query model.FirstOrDefault(); but above all I'd like to be able to filter on a field too :
var record = model.FirstOrDefault(item => item.MyProperty == true);
So how did I do it when I am not aware of <T> during compile time.
First need to get the type as DbContext.Set method returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.
public virtual DbSet Set(Type entityType)
Note here argument is the type of entity for which a set should be returned.And set for the given entity type is the return value.
var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.Name == <Pass your table name>);
now once I have this type
if(type != null)
{
DbSet context = context.Set(type);
}
Or a one liner would be
DbSet mySet = context.Set(Type.GetType("<Your Entity Name>"));
*Disclaimer: This response doesn't give a stricto sensu answer to my question. It is rather a different approach to resolve my own problem. I am aware this is a specific example for a given situation that will not work for everyone. I am posting this approach in the hope it helps someone but will not mark it as the answer as I am still hoping for a real solution.
To start with, let's accept the fact that the only useful information we can get out of the current code is whether a record exists or not.. Any attempt of a dynamic queries after that would give the RuntimeBinderException.
Then let's continue with another fact; DbContext.Add(object) and DbContext.Update(object) are not template based so we can use them to save our models ( Instead of db.A.Add() or db.A.Update() )
In my own situation, no more is required to work out a procedure
Define models a little differently
To start with, I need a field that is retrievable across all my models which should obviously be a way to identify a unique record.
// IModel give me a reliable common field to all my models ( Fits my DB design maybe not yours though )
interface IModel { Guid Id { get; set; } }
// ModelA inherit IModel so that I always have access to an 'Id'
class ModelA : IModel {
public Guid Id { get; set; }
public int OtherField { get; set; }
}
// ModelB inherit IModel so that I always have access to an 'Id'
class ModelB : IModel {
public Guid Id { get; set; }
public string WhateverOtherField { get; set; }
}
Re-purpose the dynamic queries a bit to do something we know works
I haven't found a way to do smart query dynamically, so instead I know I can reliably identify a record and know if it exists or not.
class MyDbContext : DbContext {
public DbSet<ModelA> A { get; set; }
public DbSet<ModelB> B { get; set; }
// In my case, this method help me to know the next action I need to do
// The switch/case option is not pretty but might have better performance
// than Reflection. Anyhow, this is one's choice.
public bool HasRecord_SwitchTest(string name) {
switch (name) {
case "A": return A.AsNoTracking().Any(o => o.Id == id);
case "B": return B.AsNoTracking().Any(o => o.Id == id);
}
return false;
}
// In my case, this method help me to know the next action I need to do
public bool HasRecord_ReflectionTest(string fullname)
{
Type targetType = Type.GetType(fullname);
var model = GetType()
.GetRuntimeProperties()
.Where(o =>
o.PropertyType.IsGenericType &&
o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
o.PropertyType.GenericTypeArguments.Contains(targetType))
.FirstOrDefault();
if (null != model)
return (bool)model.GetValue(this).AsNoTracking().Any(o => o.Id == id);
return false;
}
// Update and save immediately - simplified for example
public async Task<bool> UpdateDynamic(object content)
{
EntityEntry entry = Update(content, GraphBehavior.SingleObject);
return 1 == await SaveChangesAsync(true);
}
// Insert and save immediately - simplified for example
public async Task<bool> InsertDynamic(object content)
{
EntityEntry entry = Add(content, GraphBehavior.SingleObject);
return 1 == await SaveChangesAsync(true);
}
}
A little bit of plumbing to give a sense to my situation
Next, what I needed to do with that dynamic queries was a way to replicate data from a server down to my client. ( I have omitted a big chunk of the architecture to simplify this example )
class ReplicationItem
{
public ReplicationAction Action { get; set; } // = Create, Update, Delete
public string ModelName { get; set; } // Model name
public Guid Id { get; set; } // Unique identified across whole platform
}
Connecting the bits.
Now, here's the routine that connects the bits
public async void ProcessReplicationItem(ReplicationItem replicationItem)
{
using (var db = new MyDbContext())
{
// Custom method that attempts to get remote value by Model Name and Id
// This is where I get the strongly typed object
var remoteRecord = await TryGetAsync(replicationItem.ModelName, replicationItem.Id);
bool hasRemoteRecord = remoteRecord.Content != null;
// Get to know if a local copy of this record exists.
bool hasLocalRecord = db.HasRecord_ReflectionTest(replicationItem.ModelName, replicationItem.Id);
// Ensure response is valid whether it is a successful get or error is meaningful ( ie. NotFound )
if (remoteRecord.Success || remoteRecord.ResponseCode == System.Net.HttpStatusCode.NotFound)
{
switch (replicationItem.Action)
{
case ReplicationAction.Create:
{
if (hasRemoteRecord)
{
if (hasLocalRecord)
await db.UpdateDynamic(remoteRecord.Content);
else
await db.InsertDynamic(remoteRecord.Content);
}
// else - Do nothing
break;
}
case ReplicationAction.Update:
[etc...]
}
}
}
}
// Get record from server and with 'response.Content.ReadAsAsync' type it
// already to the appropriately
public static async Task<Response> TryGetAsync(ReplicationItem item)
{
if (string.IsNullOrWhiteSpace(item.ModelName))
{
throw new ArgumentException("Missing a model name", nameof(item));
}
if (item.Id == Guid.Empty)
{
throw new ArgumentException("Missing a primary key", nameof(item));
}
// This black box, just extrapolate a uri based on model name and id
// typically "api/ModelA/{the-guid}"
string uri = GetPathFromMessage(item);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:12345");
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
return new Response()
{
Content = await response.Content.ReadAsAsync(Type.GetType(item.ModelName)),
Success = true,
ResponseCode = response.StatusCode
};
}
else
{
return new Response()
{
Success = false,
ResponseCode = response.StatusCode
};
}
}
}
public class Response
{
public object Content { get; set; }
public bool Success { get; set; }
public HttpStatusCode ResponseCode { get; set; }
}
ps: I am still interested in a real answer, so please keep posting for other answer if you have a real one to share.
You could use this to get the DBSet for a specific type:
public object GetByType(DbContextcontext, Type type) {
var methode = _context.GetType().GetMethod("Set", types: Type.EmptyTypes);
if (methode == null) {
return null;
}
return methode.MakeGenericMethod(type).Invoke(_context, null);
}