The following code always throws exception
....
DataServiceContext ctx = account.CreateCloudTableClient().GetDataServiceContext();
var val = (from t in ctx.CreateTable<MyClass>("TableName")
select new {testval = t.id}).FirstOrDefault();
If I read the entity it works fine:
var val = (from t in ctx.CreateTable<MyClass>("TableName")
select t).FirstOrDefault();
Is it impossible to read just one field (or a few, I don't want to read entity) from Azure table?
Thanks in advance.
Update:
Exception data:
System.Data.Services.Client.DataServiceQueryException.
Message - "An error occurred while processing this request."
Internal Exception - code :"InvalidInput", message : "One of the request inputs is not valid."
I seem to remember that the current implementation only supports getting the full entities and does not support anonymous classes.
Another option would be to fetch the complete entity and then transform it into an anonymous type. Do note that in this case you are actually pulling full entities and then transforming them, resulting in more bandwidth consumption than would actually be needed.
Related
Let me explain my self.
With the help of LINQ i'm requesting an object to my database such :
int idGetClient=1;
Client clientToUpdate = context.Client.FirstOrDefault(p=>p.idClient == idGetClient);
in my Model, a client is related to another object called Site. So i can easily get my Site object from my SQL database just by calling :
Site siteToUpdate = clientToUpdate.Site;
So i wonder what's happening here, did LINQ ALREADY loaded up the result in my first request OR is he requesting again taking up my client information and looking up in my database ?
The second one looks the most logic to me but i want to make sure, since if what happen if the first case, it's going to cause some performance issues.
If nothing else is specified, your property Site will be lazy loaded, so just at the moment you try to access to the property, Entity will query the database server.
If a second access to the database server will cause performance issue, you can prevent that with:
int idGetClient=1;
Client clientToUpdate = context.Client
.Include("Site")
.FirstOrDefault(p=>p.idClient == idGetClient);
And you can add as many Include as you want, and you can even load properties of properties :
int idGetClient=1;
Client clientToUpdate = context.Client
.Include("Site")
.Include("Site.SubProperty")
.FirstOrDefault(p=>p.idClient == idGetClient);
The Include will force the eager loading of the specified properties.
More info here :
https://msdn.microsoft.com/en-us/data/jj574232.aspx
Presuming you are using entity framework, you can hook into the sql statements yourself and see what's going on when you access your object - e.g.
context.Database.Log = Console.Write;
It's also possible to ensure the relation is loaded by using include:
context.Client.Include("Site").FirstOrDefault(p=>p.idClient == idGetClient);
In most cases the navigation property .Site causes the Site object to be lazy loaded. That is: a specific database query is issued.
The question is a bit scarce on details, so I assume that:
.Site is a navigation property representing a relation to another table in the database.
No global configuration on early loading is done (which is possible with some linq providers).
I recommend using a SQL profiler to see what queries are actually issued to the database (see this blogpost for some reasons on why).
I have setup EF code first against my DB (specifically, a table called tblExpenseMain).
In my controller I'm trying to pass an instance of my 'ExpenseMain' class over to the view so the details can be presented. Manually creating an instance and passing it works:
ExpenseMain em = new ExpenseMain { Card_Number = "123", UniqueID_ERLineID = "blah", Item_Amount = 500, Item_Expense_Type = "something"};
return View("_Basic");
But trying to query it with LINQ like so gives me an exception:
ExpenseMain model = (from e in db.ExpenseMains
where e.UniqueID_ERLineID == transUniqueID
select e).SingleOrDefault();
It tells me to check the innerexception to find the problem. I surrounded it with a try/catch and the innerexception message was:
e.InnerException.Message = "Invalid object name 'dbo.ExpenseMains'."
Any suggestions on what I'm doing wrong? I was hoping that the linq query would just grab my single instance and go from there. Changing 'Expensemain model' to 'var model' and looking at what the var becomes, confirms it becomes an 'Expensemain' anyway.
Thanks
If your class name is different from the table name, then you have to configure EF to map them. You can use the table attribute and give the table name.
[Table("tblExpenseMain")]
public class ExpenseMain
{
//properties
}
Do you have several data access layers in your sulotion? Could it be that ExpenseMain is an old Entity, not generated from EF. Double check that there are no tblExpenseMain entity aswell or similar.
Hope this helps.
Looks like u have 2 classes here: ExpenseMain and ExpenseMains
[Note After Answer: I am actually querying in memory-objects and that's why ToTraceString doesn't work. I added this to save the reader potential time from reading my long post].
I'm using a ToTraceString command when trying to inspect how my LINQ queries end up looking. However, today my query got a bit complicated, involving a join and all of the sudden, I get this error when I try to Trace my String:
Unable to cast object of type 'd__7a`1[EGSLanguageProviderShared.DTODataType]' to type 'System.Data.Objects.ObjectQuery'.
My Query, and subsequent invocation of ToTraceString is as follows (note that System.Data.Entity has to be referenced in order for this to work). Both objects I'm querying (langDTs and langInstructionsAVDTs) are Entity Framework (.Net 3.5) objects from the same database. My Where Clause (== av.InstructionAVKey) uses a simple Value Collection Class, nothing to see there.
IEnumerable<DTODataType> dts =
(from langDT in langDTs
join langIAVDT in langInstructionsAVDTs
on langDT.DataTypeKey equals langIAVDT.DataTypeKey
where langIAVDT.InstructionAVKey == av.InstructionAVKey
select langDT).Distinct();
var sql = ((System.Data.Objects.ObjectQuery)dts).ToTraceString();
Any ideas on how I could see the LINQ translation of this Join? ::- ). I noticed that System.Data.Objects has more types of queries, but I can't get any of the ones which seem more relevant to this case, to work.
LATER EDIT:
As you recommended, I tried changing the IEnumerable to an IQueryable but that resulted in a type incompatibility compilation error ::- /.
After doing an explicit cast, I got the same error, but at Runtime (Unable to cast object of type '<DistinctIterator>d__7a1[EGSLanguageProviderShared.DTODataType]' to type 'System.Linq.IQueryable1[EGSLanguageProviderShared.DTODataType]'.`)
Additional code: my objects langDTs and langInstructionsAVDTs are:
List<DTOInstructionActiveValueDataType> langInstructionsAVDTs = CurrentLPInstructionManager.GetInstructionsActiveValuesDataTypes((from avKey in langInstructionsAVs select avKey.InstructionAVKey).Distinct().ToArray());
List<DTODataType> langDTs = _LPDataTypeManager.GetDataTypes((from dt in langInstructionsAVDTs orderby dt.DataTypeKey select dt.DataTypeKey).Distinct().ToArray());
So these objects are indeed queried immediately because they are Lists ::- ). As for DTODataType and DTOInstructionActiveValueDataType, they are simple Value Collection Classes, just public Properties, that's all.
EVEN LATER EDIT
Might be of interest that at their root, the objects I'm using are indeed declared as ObjectQuery back in the deepest layer (Entity Framework):
public global::System.Data.Objects.ObjectQuery<instructions> instructions
However, as I bring the data from over the Data Access Layer, I am converting them to Data Transfer Objects (the DTO-prefixed classes you keep seeing), which are simple Value Collection Classes (a property-by-property map of the Entity Objects which I use in order to keep the Data Model completely separated from the View and also to execute any data post-processing in the Presentation side).
Instead of typing your variable as IEnumerable<DTODataType> try IQueryable<DTODataType>, or even var.
I'm guessing somewhere in there your query is getting executed, and the results being stored as IEnumerable, and therefore no longer able to be cast as ObjectQuery
EDIT
Can you please expand your code snippet to show were both langDTs and langInstructionsAVDTs come from?
Based on your subsequent edit, it's clear that you are simply querying and joining in memory collections. That's why you can't cast to ObjectQuery, and that's also why you can't declare the query to be of type IQueryable<T>.
In other words there's no way to do a dump of the SQL being issued, because no SQL is being issued. Once you converted your data over to your in-memory collection of DTOs, you became disconnected from your database, and all your queries became linq-to-objects queries with no corresponding T-SQL being generated.
Following an introductory tutorial for the new DomainService in Silverlight 4 RIA, I got an unexpected exception. When I perform an update the property EntitiesInError[index].EntityConflict.PropertyNames throws the following exception:
InvalidOperationException: PropertyNames are not available for delete conflicts.
Service method executed:
public void UpdateSr_Supplier(sr_Supplier currentsr_Supplier)
{
// UPDATE the existing sr_Supplier
this.ObjectContext.sr_Supplier.AttachAsModified(currentsr_Supplier, this.ChangeSet.GetOriginal(currentsr_Supplier));
}
From the answer on this thread I gather that I should rather use Silverlight-enabled services with custom service objects (DataContract and DataMember), then assign the values of these custom service objects to the actual server objects (generated from the DB model, be that Linq to Sql or the Entity Data Model), and manually call SubmitChanges() on the DataContext.
PropertyNames will throw an exception if the error you're dealing with is a deletion conflict, this is normal. You should be looking for the underlying database error, which may be neglecting to set a non-null value or a primary key violation, etc.
So I've started to add Entity Framework 4 into a legacy web application (ASP.NET WebForms).
As a start I have auto-generated some entities from the database. Also I want to apply Repository Pattern.
There is an entity called Visitor and its repository VisitorRepository
In VisitorRepository I have the following method:
public IEnumerable<Visitor> GetActiveVisitors()
{
var visitors =
from v in _context.Visitors
where v.IsActive
select new Visitor
{
VisitorID = v.VisitorID,
EmailAddress = v.EmailAddress,
RegisterDate = v.RegisterDate,
Company = v.Company,
Position = v.Position,
FirstName = v.FirstName,
LastName = v.LastName
};
return visitors.ToList();
}
Please note that Visitor has more properties than those, I just don't want to get everything because there are some heavy TEXT fields.
That List is then bound to a repeater and when trying to do <%# Eval('EmailAddress') #%> it throws the following exception.
The entity or complex type 'Model.Visitor' cannot be constructed in a LINQ to Entities query.
A) Why is this happening? How I can workaround this? Do I need to select an anonymous type and then use that to partially initialize my entities??? I don't want to make a SELECT * because there are some heavy TEXT columns I don't need here
B) Why every example I've seen makes use of 'select new' (anonymous object) instead of initializing a known type? Anonymous types are useless unless you are retrieving the data and showing it in the same layer. As far as I know anonymous types cannot be returned from methods? So what's the real point of them???
Thank you all
a) It's happening because Visitor is an entity. You could say the following with the understanding that you won't be able to update the database via the resulting objects outside the data context in the repository:
var visitors =
from v in _context.Visitors
where v.IsActive
select v;
b) I don't know what example you are looking at but you are right to say that passing a collection of anonymous types from a repository in the data layer to the GUI isn't what you want. You can either use self-tracking entities or data transfer objects (DTOs). This MSDN article explains your options in detail.