Exception using Linq query with EF Code first on SQL Server table - c#

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

Related

Pass string of "<TableName>.<ColumnName>" as a Where() condition generates error: "No property or field '<TableName>' exists in type '<TableName>'"

Currently, I build query statement by using dynamic-linq library.
And I have an issue when I execute this query:
query = query.Where("Table1.Column2.Contains(#0)", new string[] { "test" });
FYI:
Table1: a table name in my database
Column2: a column name inside Table1
As a result, it throws an error:
No property or field 'Table1' exists in type 'Table1'
I have made sure, the naming are correct. A friend of mine, he also uses exactly the same library and he can execute it successfully in different database, MSSQL 2014. I am using MSSQL 2008.
When I try to do it in different way like:
query = query.Where("Column2.Contains(#0)", new string[] { "test" });
It works fine..
I am wondering, in my case, I have to use the first approach instead. That's why, what am I doing wrong with it?
My understanding is that Dynamic Linq is still operating on objects, not passing what you write directly through to SQL? So you can only add conditions on things that are properties of the underlying object. Now these may be defined as being populated from various columns in a database, but they don't have to be...
I think you're basically trying to do this sort of thing:
class x
{
int SomeProperty{get;set;}
}
...
...
var instance = new x();
instance.SomeProperty = 1;
//compile Error: x is not a property of an instance of x
if (instance.x.SomeProperty==1)
{
// ..Do things
}

How do you query several tables at once given a list of table names as strings?

So I work at a company where there are several tables with different names, but the exact same structure (date, time, value). What I would like to be able to do is have my program (C# or LINQ/LINQPad) run through these tables and query out a specific row so I can make sure they have all been updated properly. Is this doable?
So far my train of thought has been this. Knowing that each table name will give it a different class, I'm trying to generically get the values out of the table. I am able to get the table by using the code here
DataContext dc = new DataContext();
var myTable = (ITable)dc.GetType().GetProperty("Table").GetValue(dc, null);
My problem is I'm trying to get the columns out of this table using a similar method. However, the below is throwing an error:
foreach(var e in myTable)
{
double myValue = (double)e.GetType().GetProperty("Value").GetValue(e, null);
}
So when I took a look all the properties of e.GetType(), I noticed it had 2, one of which was Context, so I went exploring there. However, the next layer down seems to be a dead end of metadata with no actual data coming out of my loop. Am I even heading in the right direction? Once I get this hurdle, it would be easy enough for me to make a list and get my results out that way. Any help would be appreciated. Thanks.
If you need to query many tables by primary key (EntityKey in db context), then
ObjectContext has a method called GetObjectByKey that allows you to get object by EntityKey
So, you need to construct just a EntityKey. According to the MSDN article, it is pretty simple,
DataContext dc = new DataContext();
EntityKey key = new EntityKey("DataContext.Table","Id", 123);
dynamic entity = dc.GetObjectByKey(key);
You can create an interface that is common for all tables (entites) that have the same structure and cast your object to the interface, or just use dynamic.

StackOverflowException trying to return a Linq query result as a List through a WCF Service

I have had a lot of problems with this stuff and I can't solve it even with a simpler example.
I've a WCF service that returns a list of objects (from my Entity Model).
The model only has 2 tables:
Person, with id, name and office_id (foreign key)
and Office, with id and address
I'm making a really simple linq query that returns the first of these people. This is working ok, even the "ToList()" method works ok.
The problem is that when I try to return it through the service it crashes with a "An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"
I think it's related to the Navigation Properties when it tries to serialize the Person object. These Navigation Properties appear in both the Person and Office model, the Person table has a "Office" Navigation Property, but Office table has a "Person" Navigation Property too!!
I think these navigation properties can be useful for other scenarios but I can't find a way to say not to load those contents or at least not to serialize and return it through the service!!
This is the linq query (this works, the list really has one person inside):
var query = (from chosen in entities.person
select chosen).First<person>();
return query.ToList<person>();
Does anybody has ever seen something like this? I have had several WCF-Linq projects before and I never had any similar issue.
Thanks in advance.
It sounds like you have a circular reference problem, try decorating your Person and Office class with:
[DataContract(IsReference = true)]
Finally I solved it setting both ProxyCreationEnabled and LazyLoadingEnabled as false in the entities object:
Model.Entities entities = new Model.Entities();
public ServicePeople()
{
entities.ContextOptions.ProxyCreationEnabled = false;
entities.ContextOptions.LazyLoadingEnabled = false;
}
Assuming that your WCF service uses the default DataContractSerializer, try decorating the navigation properties with IgnoreDataMemberAttribute.

Querying conceptual model with Entity SQL

Thought I read somewhere that you in fact can query your conceptual model with Entity Sql, using string based queries as such:
class DBSetTest<T> : List<T>
{
DBEntities db = new DBEntities();
public DBSetTest()
{
ObjectQuery<T> test = new ObjectQuery<T>("SELECT Name FROM Sessions WHERE Name = 'sean'", db);
foreach (var v in test)
{
this.Add(v);
}
}
}
Where 'Sessions' is a custom Entity Type I defined with a 'DefiningQuery'. I would otherwise query it with normal linq syntax. Does Entity SQL only query the store or can it query my conceptual model just like LINQ-to-Entities does? If so not sure I have the right syntax, since it probably isn't sql syntax. My goal is to create a sort of custom generic list here, where I can write dynamic queries against my conceptual model.
I get the following error:
'Name' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near simple identifier, line 1, column 43.
I think, It is not valid Entity SQL sintax,
probably you must add some keyword like this :
SELECT VALUE s.Name FROM your_ObjectContext_name.Sessions AS s WHERE s.Name = 'sean'
The error you get says that you must put it. before Name, like this:
"SELECT it.Name FROM Sessions WHERE it.Name = 'sean'"

Retrieve a particular field value from Azure table

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.

Categories

Resources