Hi I'm now learning about entity framework and still a beginner. Now, I've been having a problem with deleting multiple data in my database. Here is a piece of my database:
Please click to see the image for database
For example i wanted to delete all data that has a brandId of 2. I tried using this code:
int brandId = (from i in context.brands where i.name == name.Text select i.brandId).First();
var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();
if (bay2 != null)
{
context.logoes.Remove(bay2);
context.SaveChanges();
}
But it only deletes one data, which is logoId 3. It did not delete logoId 4. What am i doing wrong in my query? How to delete all data that has brandId 2 using entity framework?
This line is pulling only one object:
var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();
Because of the FirstOrDefault.
Remove the FirstOrDefault. Then use RemoveRange:
var bay2 = (from g in context.logoes where brandId == g.brandId select g).FirstOrDefault();
if (bay2.Any())
{
context.logoes.RemoveRange(bay2);
context.SaveChanges();
}
Try to use .ToList() method instead of First(). Then Iterate over this for example list using foreach and delete these objects, or delete whole range.
Related
I have tow tables - OrderRequisition and Order. I can show all the records from OrderRequisition table using linq query:
var list = (from r in db.OrderRequisition
select new SalesOrderViewModel
{
OrderId = r.OrderId ,
OrderNo = r.OrderNo
}).ToList();
I want to show only those records from OrderRequisition table which are not included in Order table. Any clue
Thanks
Partha
A simple approach that might be efficient enough because your database is able to optimize it:
var list = db.OrderRequisition
.Where(or => !db.Order.Any(o => o.OrderId == or.OrderId))
.ToList();
(skipped the SalesOrderViewModel initialization because not relevant for the question)
I have two tables, from 1st table i want to get all records and from 2nd table i want the max id value of that record. I am using entity framework in asp.net c#.
i tried the below code but it takes only single record from first table i.e tblblogs. and leave all the records, how to get all those records by using this query? plz help me out I'll be very grateful to you. Thanks !
var query= (from c in db.tblBlogs join a in db.tblBlogMedias on c.id
equals a.BlogId where c.id==db.tblBlogMedias.Max(p=>p.id)
select new
{}
If I understood, you want to get an object with specific fields of Blogs and a list of tblBlogMedias.
You could try this code:
var query2 = (from c in db.tblBlogs
orderby c.Id descending
group c.tblBlogMedias by new { c.Id, c.Name } into gb //It will show Id and name of tblBlogs, you can use more fields if you want
select new {
Id = gb.Key.Id,
Name = gb.Key.Name, //I don't know if you have this field, but you should change it
SecondTable = gb.ToList()
})
.OrderByDescending(o => o.Id) //this orderby with FirstOrDefault() replace where c.id==db.tblBlogMedias.Max(p=>p.id)
.FirstOrDefault();
I am learning ASP.net and I have come to the point that I want to insert, update, delete records in a database.
Currently I am trying to read out values out of 2 tables using "join" but when I display the results in a grid the Foreign Key values are still like : 2, 1, 2,... Instead I want them to be to coresponding words.
This is the current query I am using:
from p in dc.Personeels join a in dc.Afdelingens on p.fk_personeel_afdeling equals a.pk_afdeling_id select p
Does anyone know what I am doing wrong?
Try this query
var query = from p in dc.Personeels
join a in dc.Afdelingens on p.fk_personeel_afdeling equals a.pk_afdeling_id
select new
{
id = p.id, // your id from table dc.Personeels
name = a.name // Name from table dc.Afdelingens
} into x
select x;
I am trying to delete the movie from rentals table if it is selected from the listbox and it is working but i also need to remove datas connected to the movie from rentingpeople table
Rentals table contains the movieid which is in the listobox and personid which can be also found in rentingpeople and should get deleted the full row if they matches.
var search = (from g in db.Rentals where g.Movietitle == (string)lBfilmlista.SelectedValue select g).First();
foreach (var c in db.Rentingpeople where c.personid==search.personid).First();
{
db.Rentingpeople.DeleteObject(c);
}
db.Rentals.DeleteObject(search);
db.SaveChanges();
there is code error at where c.personid==search.personid ) ; expected
Problem is with First at the end of foreach loop, and also mixing query syntax with method syntax.
So your code should be:
var search = (from g in db.Rentals where g.Movietitle == (string)lBfilmlista.SelectedValue select g).First();
var rowsToBeDeleted = db.Rentingpeople.Where(c=> c.personid==search.personid).ToList();
foreach (var item in rowsToBeDeleted)
{
db.Rentingpeople.DeleteObject(item);
}
db.Rentals.DeleteObject(search);
db.SaveChanges();
You can also setup Cascade on Delete rules for your tables.
I need to update a column in a table which contains a lot of rows. Each row has a some large TEXT columns in it, which i do not need for my update.
I'm using LinqPAD, and this is roughly, what i wanna do:
(from s in Table
where s.FK_ID == null
select new{s.FK_ID, s.Datum, s.PBNummer}).ToList()
.ForEach(s => s.FK_ID = new Guid(...some new guid here...));
SubmitChanges();
This does not compile, as the properties of an anonymous class type are read-only.
If I do
(from s in Table
where s.FK_ID == null
select s).ToList()
then I can update and save, but all columns are loaded, which takes a very long time and causes memory problems.
Is there a way to only load some columns but still have an object that i can update and save using SubmitChanges? Or do i have to switch to SQL statements?
Way to update specific columns of a database record in Linq to SQL is to create a View on the table containing large columns, and only include the “short” columns:
CREATE VIEW [dbo].[V_FooMax] AS
SELECT OID, ID
FROM dbo.FooMax
Since views based on single tables are updatable, an update on the view is performed as an update on the table:
using (var database = new DataContext())
{
var fooView = database.V_FooMaxes
.Where(foo => foo.OID == OID).FirstOrDefault();
fooView.ID = newID;
database.SubmitChanges();
}
Reference: http://devio.wordpress.com/2011/01/15/updating-a-single-column-in-linq-to-sql-using-a-view/
Also you can look at: http://devio.wordpress.com/2011/01/16/updating-a-single-column-in-linq-to-sql-summary/
Firstly, if you don't have a primary key in the database, then you wouldn't be able to update via Linq-To-Sql. If you have a primary key, but just don't know which it is, you can find it in Linqpad by doing something like
var table = (from t in Mapping.GetTables()
where t.TableName == "[Table]" select t).SingleOrDefault();
(from dm in table.RowType.DataMembers
where dm.DbType != null && dm.IsPrimaryKey
select dm.Name)
.Dump("Primary Key");
Once you know the primary key, you can do something like the following, (I'm assuming the primary key is called Id)
var oldList = (from s in Table
where s.FK_ID == null
select new{s.Id , s.FK_ID, s.Datum, s.PBNummer}).ToList() ;
This is similar to your query, except I have added the primary key
foreach(var r in oldList)
{
Table t = new Table();
t.Id = r.Id ;
Table.Attach(t);
t.FK_ID = new Guid(...some new guid here...));
}
SubmitChanges();