How can I make this LinqToSQL query work? (SqlExecption) - c#

The following code gives me an SqlException: Invalid object name 'dbo.studentsCourses'
OO theCourse = subject.Course;
var students = dc.studentsCourses.Where(x => x.course == theCourse).Select(x => x.student);
I tried the following code instead but I also get an Exception.
My original question was asked on Aardvark and can be read bellow:
var allStudents = from s in dc.students select s;
List thestudents = new List();
foreach (student s in allStudents)
{
if (s.courses.Contains(theCourse))
{
thestudents.Add(s);
}
}
I did a right click, "run custom tool" on my dbml and checked my names of my tables and entities. The project compiles but I get an Exception at runtime on this line:
"if (s.courses.Contains(theCourse))"
Any ideas?
Original question on Aardvark:
How do I do a LinqToSQL query that
gives me this: I want to select all
students that attended a certain
lesson. The lesson is from a certain
course. So select the course the
lesson is from. Now select all the
students that are following that
course. There is a many-to-many
relationship between the students and
the courses table in my DB. I already
extended my LINQ entities to be able
to select student.Courses and
course.Students using this method:
http://www.codeproject.com/KB/linq/linq-to-sql-many-to-many.aspx

Your link to sql classes don't match your db schema or your db does not contain a table or view called studentcourses. You need to adjust either your classes or db so they match.

You could start debugging this problem by visualizing the query that is generated by the LinqToSQL. The Gu has written a blogpost on this a while ago:
http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx
Just copy/paste the query in your favourite database management application and run it against the database. It should become clear what the error is. If there are still some crazy things happening, just update your question?
Hope this helps!

First check your database to see if there is really a table or view name studentsCourses.
If there is then try to regenerate to dbml file and then try again.

I'm not sure... but you may try this one:
var xxx = dc.Include("studentsCourses")
.studentsCourses
.Where(x => x.course == theCourse)
.Select(x => x.student)
.ToList();

Related

How to set up persistent object for one-to-many and many-to-many at same time? [DevExpress]

I have an issue with next scheme, I attached it.I want to query from my database with only one object with "Manufacturer" class. Like:
var res = new XPQuery<Manufacturer>(session);
And then query all info that are related to my condition in LINQ.
I have tried XPLiteObject, XPObject, Association attribute, NoForeignKey Attribute, XPOCollection and a lot of stuff but nothing didn't help me.
I have tried a lot of approaches and every time I have new exception like:
SelectMany - method is not supported.
Can't set foreign key in table.
Duplicate primary key.
My question is: how to describe classes for normal extraction data from db?
UPD:
My solution now is: to use .ToList() at every object
and then use linq-query for join data and make needed query.
var manufacturer = new XPQuery<Manufacturer>(session).ToList();
var cars = new XPQuery<Car>(session).ToList();
var countries = new XPQuery<Country>(session).ToList();
var result = from m in manufacturer ....
So, I have found a solution to my question.
I downloaded DevExpress that can add templates for visual studio.
Then I select Add new item to my project named "DevExpress ORM DataModel Wizard".
This wizard can create persistent objects for existing database.
After that I can query database with next syntax:
var manufacturer = new XPQuery<Manufacturer>(session).Select(x => x....)...;
But if you want to use .SelectMany() in your LINQ query you should use .ToList() and then use .SelectMany(). I faced with a lot of issues when I have tried to join or perform some other LINQ related operations. Well, if you got some errors, firstly after .Select() try .ToList() and then perform your operation.

How to create a database query with LINQ to erase rows by having a list of ID's and by avoiding loops

I am a newbie with LINQ so I would appreciate if you could explain thoroughly your answer. What I am trying to do is that I have a table called ContentTable. This ContentTable has different columns and rows and one of the columns is using EntityId's.
In my method I receive from somewhere a list of ID's in a List. I don't want to iterate over this list and query the database for each ID because that would be expensive, but I want a query which uses the ID's in the list to match with the EntityID's in the table, and if there is such a match, I erase the whole row from the table. May you kindly help me? Thanks in advance!
You can use Entity Framework Extensions to do that. Something like:
this.Container.Devices.Delete(
o => o.Id == 1,
o => o.Id == 2
);
Some thing like this might help , however if the table is too big (millions) Linq to sql will lock the table. Also for each entity it issues a single T-SQL Delete statement to delete the entity.
public void DeleteContents(List<int> entityIds)
{
using (Yourcontext db = new Yourcontext())
{
IQueryable<ContentTable> contents = db.ContentTable.Where((x) => ids.Contains(x.EntityId));
db.ProductComplianceRules.DeleteAllOnSubmit(contents);
}
}

Can i use nested queries for database entities in LINQ?

I'm working on an ASP.Net application which uses a SQL-Server DB and database entities.
Further i got three database entities which are dependend on each other.
This is the dependency hierarchy:
Instance (Key: InstanceID)
CustomField (Key: CustomFieldID, InstanceID)
CustomFieldData (Keys: CustomFieldDataID, CustomFieldID)
CustomFieldData_Person (Keys: CustomFieldData_PersonID, CustomFieldDataID)
I can find out the entries from the entity CustomField by this with the InstanceID:
var customFieldEntries = DB_Instance_Singleton.getInstance.CustomField.Where(x => x.InstanceID == instanceId);
Now i want to find out all entries from CustomFieldData_Person which belong to the hierarchy with the InstanceID as key.
In SQL i would write something like this:
SELECT * FROM CustomFieldData_Person WHERE CustomFieldDataID in (
SELECT * FROM CustomFieldData WHERE CustomFieldID in (
SELECT * FROM CustomField WHERE InstanceID = instanceId))
Unfortunately i'm absolutely new to LINQ.
So my question is, how can i write such a nested query in LINQ (aacording to the first code example above)?
Thanks in advance!
Firstly if you create your ER model correctly you will have most of that logic already set up for you
Person would have a property Person.CustomData which would have Properties for Field and Value so you can just navigate the object structure
however if you dont have that then you can just convert the in statements to Contains
CustomFieldData_Person.Where(cfdp=>CustomFieldData.Where(nested query for CustomFieldData).Contains(cfdp.CustomFieldDataID )
I think this link could be a good starting point for your question. Anyway take a look at Pranav's comment, it points to a helpful question

Linq Foreign Key Select

I have two tables with a one (Articles) to many (Details) relationship. Details may not contain any data for the particular Article entry.
Articles: Id, Title, Numb (PK), Name
Details: Id (PK), Person, Numb (FK), Name
In the Entity Framework, there are the appropriate Navigation properties and it shows the correct One:Many relationship.
What I want to do is get all Articles that match the end user's query (by 'Name') as well as all, if any, data from the Details table (Id, Person, Numb, Name).
What I'm stuck on is right now I can query Articles just fine (var article = db.Articles.Where(b => b.Name.Equals(name));), but while the result does include a HashSet for Details.Numb on each row of Articles, there is no data in that HashSet. There are appropriate corresponding entries in the database for Article.Numb => Details.Numb.
Actually there is two ways to achieve this.
Enable Lazy Loading.
Call Include method as other answers says.
Using Lazy Loading see msdn article for more detail.
db.ContextOptions.LazyLoadingEnabled = true;
Using Include method
var article = db.db.Articles.Include("Details").Where(b => b.Name.Equals(name))).FirstOrDefault();
You need to tell EF to include the details in the result set after the query is executed (and connection closes):
var article = db.Articles
.Include("Details")
.Where(b => b.Name.Equals(name))
.FirstOrDefault();
Use .Include() on the navigation property, it will bring the entire inner object in the query result. It's only automatic if you filter or select items from the inner object, otherwise you have to manually request an include.
Example:
var allProducts = _db.Products.Include(d => d.Producer).ToList();
Always go with Include instead of lazy loading if you're not sure.

ado.net entity framework delete rows

I may be completely blind and stupid, but I cannot find any method generated by ADO.NET Entity Data Model that would somehow delete rows from my table. I didn't want to create a custom query. So how do I do that? Please help.
I don't have the method DeleteOnSubmit... don't know why. This is the code I wanted to use.
var deleteOrderDetails =
from details in db.OrderDetails
where details.OrderID == 11000
select details;
foreach (var detail in deleteOrderDetails)
{
db.OrderDetails.DeleteOnSubmit(detail);
}
db.SubmitChanges();
A couple of alterations needed:
db.DeleteObject(detail);
and
db.SaveChanges();
Kindness,
Dan
PS: Have you been using Linq to SQL and then swapped to the Entity Framework?
Here's another way (thanks to this answer)
I assume you have the Orders table, and OrderDetails is related to it via OrderID.
var order = db.Orders.FirstOrDefault(o=> o.OrderID == 11000);
if(order != null)
{
order.OrderDetails.Clear();
db.SaveChanges();
}
This should delete all the order details associated with that order.
edit: fixed the code

Categories

Resources