If i execute this part of the code:
var adressenDetailses = new KlippsTestEntities().AdressenDetails.Count();
the variable adressenDetailses has the value 961. (That means the enumeration has values)
If I want to check the values of the IEnumerable AdressenDetails during debugging then Visual Studio says
'For the functionevalution all threads have to be executed'.
I execute the Thread by clicking the reload icon. Now Visual Studio says:
'The expression can not be evaluated. The process is not supported.
Unknown error: 0x80070057.'
Does anyone knows the answer to how I can fix the problem?
Entity Framework is lazy.
I mean this is a good way. It will only fetch the data it needs to fetch up-front. Any linking values - like links/FKs to other tables - will get only when it is asked.
This is why you are are seeing this behavior when you are debugging, but if you wrote the full code out and ran it normally it would produce the correct values.
You can enable "eager loading" using an Include line
var adressenDetailses = new KlippsTestEntities()
.Include(x => x.AdressenDetails) //tells EF to eager load that link
.Select(x=> x.AdressenDetails); //"I would only like to see data on the details"
var addressCount = adressenDetailses.Count();
Now you should be able to debug the first line and see the specific details of that object.
Side note: you don't need to add the .Select(x=> x.AdressenDetails); clause.
Related
When I start typing a linq query, the "from" keyword is not suggested by default resulting in it auto completing on some other variable which is massively frustrating.
What I'm trying to type: var myResult = (from x in myList)
What I've actually typed: var myResult = (from"SPACEBAR"
What I end up with:
var myResult = (someOtherVariableThatHasFromInIt)
PS. If you tell me to do the linq query a different way you're missing the point.
If this is VS there is a button that switches from auto-completion to suggestions (shortcut: Ctrl+Alt+Space), the difference beeing that in suggestion mode you have to use tab (space bar doesn't insert automatically). The only problem is that when you close VS it returns to standard mode.
If it's VS Code, add the following to "settings.json"
"editor.acceptSuggestionOnCommitCharacter": false,
"editor.acceptSuggestionOnEnter": "off",
I have a sql server with the table "contacts", in this table i have column "clicks" of type int, i want to increment its value without making a query.
This is a copy of: "Entity framework update one column by increasing the current value by one without select"
the solution that suggested there is using EntityFramework.Utilities
the problem is that its not a IQueryable extension like EntityFramework.Extended and that makes it hard to implement for me.
the question is there any other way/solution to incremenet int value on sql with using IQueryable(without actually writing sql query)?
the result of the IQueryable query should look like:
UPDATE Contacts SET clicks=clicks+1 WHERE id=8432
I just found the solution after some research and testing, actually EntityFramework.Extended do exactly what i want it to do, if you want to increment a column just call the Update method with adding assignment:
db.Contacts.Where(c => c.Id == id).Update(c => new Contact { Clicks = c.Clicks + 1 });
After checking the source code of EntityFramework.Extended and debugging it i saw that the query that executed in the end is exactly what i wanted,
so thanks everybody for trying to help, the solution were right under my nose ;-)
In ADO.Net I created a DAL file that took parameters from the user and if they were not null, the query got extended based on if statements. Now I want to do the same in Entity Framework.
I have searched a number of sites including Stack Overflow but failed to get my satisfactory answer.
for Reference, the following link also could not help me
Select Query with Where condition depending on list values in asp.net
the required scenario is
cmd.text = "SELECT FROM tbl_name WHERE id>0 "
if(param_value != null)
{
cmd.text += " AND (param_name = '#param_value')";
if(!cmd.contains("param_name"))
cmd.parameters.addwithvalue("param_name", #param_value);
cmd.parameters["param_name"] = #param_value;
}
// proceed further with cmd.text
please ignore the syntax right now, I just wanted to convey my concept of what I want to do.
I want to apply the same concept for Entity Framework
Well two days back I found a scenerio in wheich the query (text) was built in an aspx.cs file and it was passed as it is to a custom built function in DAL which passed the text to cmd.text and processed the rest of retrieval in an ADO.net style.
This method is potentially dangerious as anyone with a bit knowlege can break this security down to grounds.
I want to create a query that has parameters as well as its vales like I have shown in above code block.
Using LINQ-to-SQL:
var param_value = 0;
db.tbl_name.Where(x => x.id > 0).Where(x => x.some_property == param_value).ToString();
If you look at the generated SQL, you'll see that's its parameterized (it picks the param_names, though).
I added the ToString() at the end, just so you could see the resulting SQL; based on OP, I'd say to leave this off, and keep modifying the query further directly in LINQ, rather than converting to SQL as a string and concatenating.
I just found out working with Entity framework is a totally different world that classic approach. In here, we work with models/objects and their relationships with each other and we access them based on that relationship. So to answer the question we need to get that model first like
Movie movie = db.Movies.Find(id);
and than from that, we get a model object which does have different properties in it like title, IMDb, rating etc.
We get them repeatedly using where clause as below:
db.Where(movies=>movies.IMDb==10).Where(movies=>movies.title=="The Game Plan")
this all is equal to the following in classic approach
AND (IMDb = 10) AND (title = 'The Game Plan')
following that, one can extend his query as much as he likes.
Again ignore the syntax here because I am here t convey the idea only.
For reference, the following links might be helpful keeping in mind the context i have explained.
Multiple where conditions in EF - StackOverflow
I keep getting the following InvalidOperationException:
The relationship between the two objects cannot be defined because
they are attached to different ObjectContext objects.
when trying to do the following code:
newCorr.ReqCode = (from req in context.ReqCodeSet
where req.Code.Equals(requirement.Code)
select req).FirstOrDefault();
Just before this line, I am doing the following:
foreach (Requirement requirement in myInformation.Reqs)
{
MyHwReqCorr newCorr = new MyHwReqCorr();
newCorr.HwItem = Dictionaries.Instance.HwIdHwRecordDictionary[requirement.Id];
So what I'm doing is parsing through the my Information.Reqs list, creating a new instance of MyHwReqCorr, setting the HwItem to an item that was stored in a dictionary earlier on, and then setting the ReqCode by using a LINQ to SQL command which to look in a table for a req code that matches the one I'm passing in. Any help would be greatly appreciated. Any info you need, I'd be happy to provide.
EDIT: Right before I call this foreach, I can call this (as testing to verify that I can access the db):
List<ReqCode> reqCodeList = (from req in context.ReqCodeSet select req).ToList();
And I never get any errors with that. But when I try to set an item in that list (using the where extension method like:
newCorr.ReqCode = reqCodeList.Where(t=>t.Code == requirement.Code).FirstOrDefault();
or using a dictionary as done similar to the newCorr.HwItem, I get the main error.
EDIT2: I have also noticed something weird happening: When I initially run, with any setup (my original or the variable method or the method Rony posted), it works. But any subsequent run, meaning if I stop debugging and start debugging again, it fails with that error. Only when I kill all instances of excel (which is running in the background generating a log for viewing later on) and wait about 2-3 minutes, does it work again and then follows the same situation as before...passing the first time, failing immediate subsequent times.
EDIT3: It's definitely not Excel related as I prevented Excel from starting and I still get that error. But I did notice that if I wait some time, and try again, it works....sometimes.
Are you retrieving all items on the same thread/context? Try retrieving the items on same thread.
newCorr.ReqCode = (from req in context.ReqCodeSet
where req.Code equals requirement.Code
select req).FirstOrDefault();
OR
newCorr.ReqCode = context.ReqCodeSet
Where( r => r.Code == requirement.Code)
.FirstOrDefault();
I have 2 related Linq to SQL questions. Please see the image below to see what my Model looks like.
Question 1
I am trying to figure how to eager load the User.AddedByUser field on my User class/table. This field is generated from the relationship on the User.AddedByUserId field. The table is self-referencing, and I am trying to figure out how to get Linq to SQL to load up the User.AddedByUser property eagerly, i.e. whenever any User entity is loaded/fetched, it must also fetch the User.AddedByUser and User.ChangedByUser. However, I understand that this could become a recursive problem...
Update 1.1:
I've tried to use the DataLoadOptions as follows:
var options = new DataLoadOptions();
options.LoadWith<User>(u => u.ChangedByUser);
options.LoadWith<User>(u => u.AddedByUser);
db = new ModelDataContext(connectionString);
db.LoadOptions = options;
But this doesn't work, I get the following exception on Line 2:
System.InvalidOperationException occurred
Message="Cycles not allowed in LoadOptions LoadWith type graph."
Source="System.Data.Linq"
StackTrace:
at System.Data.Linq.DataLoadOptions.ValidateTypeGraphAcyclic()
at System.Data.Linq.DataLoadOptions.Preload(MemberInfo association)
at System.Data.Linq.DataLoadOptions.LoadWith[T](Expression`1 expression)
at i3t.KpCosting.Service.Library.Repositories.UserRepository..ctor(String connectionString) in C:\Development\KP Costing\Trunk\Code\i3t.KpCosting.Service.Library\Repositories\UserRepository.cs:line 15
InnerException:
The exception is quite self-explanatory - the object graph isn't allowed to be Cyclic.
Also, assuming Line 2 didn't throw an exception, I'm pretty sure Line 3 would, since they are duplicate keys.
Update 1.2:
The following doesn't work either (not used in conjuction with Update 1.1 above):
var query = from u in db.Users
select new User()
{
Id = u.Id,
// other fields removed for brevityy
AddedByUser = u.AddedByUser,
ChangedByUser = u.ChangedByUser,
};
return query.ToList();
It throws the following, self-explanatory exception:
System.NotSupportedException occurred
Message="Explicit construction of entity type 'i3t.KpCosting.Shared.Model.User' in query is not allowed."
I am now REALLY at a loss on how to solve this. Please help!
Question 2
On every other table in my DB, and hence Linq to SQL model, I have two fields, Entity.ChangedByUser (linked to Entity.ChangedByUserId foreign key/relationship) and Entity.AddedByUser (linked to Entity.AddedByUserId foreign key/relationship)
How do I get Linq to SQL to eageryly load these fields for me? Do I need to do a simple join on my queries?, or is there some other way?
Linq to SQL eager loading on self referencing table http://img245.imageshack.us/img245/5631/linqtosql.jpg
Any type of cycles just aren't allowed. Since the LoadWith<T> or AssociateWith<T> are applied to every type on the context, there's no internal way to prevent an endless loop. More accurately, it's just confused on how to create the SQL since SQL Server doesn't have CONNECT BY and CTEs are really past what Linq can generate automatically with the provided framework.
The best option available to you is to manually do the 1 level join down to the user table for both of the children and an anonymous type to return them. Sorry it's not a clean/easy solution, but it's really all that's available thus far with Linq.
Maybe you could try taking a step back and seeing what you want to do with the relation? I'm assuming you want to display this information to the user in e.g. "modified by Iain Galloway 8 hours ago".
Could something like the following work? :-
var users = from u in db.Users
select new
{
/* other stuff... */
AddedTimestamp = u.AddedTimestamp,
AddedDescription = u.AddedByUser.FullName,
ChangedTimestamp = u.ChangedTimestamp,
ChangedDescription = u.ChangedByUser.FullName
};
I've used an anonymous type there for (imo) clarity. You could add those properties to your User type if you preferred.
As for your second question, your normal LoadWith(x => x.AddedByUser) etc. should work just fine - although I tend to prefer storing the description string directly in the database - you've got a trade-off between your description updating when ChangedByUser.FullName changes and having to do something complicated and possibly counterintuitive if the ChangedByUser gets deleted (e.g. ON DELETE CASCADE, or dealing with a null ChangedByUser in your code).
Not sure there is a solution to this problem with Linq to Sql. If you are using Sql Server 2005 you could define a (recursive like) Stored Procecdure that uses common table expressions to get the result that you want and then execute that using DataContext.ExecuteQuery.