Deleting cell value using EntityFramework - c#

This is my database table called 'AssignedExercises':
I'm trying to delete this value:
This is my code...
var b = db.AssignedExercises.Where(m => m.Data_UserID.Equals(3)).FirstOrDefault();
db.AssignedExercises.Remove(b);
db.SaveChanges();
but it deletes a whole row. How should I change it?
Thanks!

You are explicitly removing the row, which is represented by the entity object. Columns on the other hand are represented by properties on the object. As a result, you need to update the property on the object itself. Also, you can use FirstOrDefault() directly...the Where() is redundant.
var b = db.AssignedExercises.FirstOrDefault(m => m.Data_UserID.Equals(3));
if (b != null)
b.Monday = null;
db.SaveChanges();

I'm assuming you want to clear out the value, not "delete the cell"? You can't really "delete the cell" because it is represented by the column "Monday". So for that row, you can clear the value out (e.g. set to NULL or an empty string perhaps?). If you were to "delete" it, you would be removing the entire column for all rows.
I would simply do this:
var b = db.AssignedExercises.Where(m =>m.Data_UserID.Equals(3)).FirstOrDefault();
b.Monday = ""; // if you want empty string, or set to DbNull
db.SaveChanges();

That's the expected behaviour. You can edit the value using:
b.Monday = null;
and then call
db.SaveChanges();

You have to update the value instead of using remove. Remove, as you have discovered, deletes the row.
var b = db.AssignedExercises.Where(m => m.Data_UserID.Equals(3)).FirstOrDefault();
b.Monday = NULL; //or DbNull if you need to
db.SaveChanges();

Related

New column is added automaticlly when filling datagridview

I'm using linq to filling my datagrid view with this method:
public List<HopDongCungCap> XemHopDong()
{
return QL.HopDongCungCaps.ToList();
}
and this is my
Result
My dbo.HopDongCungCap just has 1-4 column
but i dont know why it appears the 5th column
Note that dbo.NhaCungCap has a relationship with dbo.HopDongCungCap
Thank you for watching my question!
A solution would be to project the wanted results with Linq like this:
var result = QL.HopDongCungCaps.Select(x => new
{
MaHD = x.MaHD,
TenHD = x.TenHD,
ThoiHan = x.ThoiHan,
NCC = x.NCC
}).ToList();
Note that I leave 'NhaCungCap' out from the result.
This will create a anonymous type.
But you can create a classobject or DTO(Dummy Transfer Object) and project the result that object. and assign that to the datagridview. (.Select(x=> new YourClassDTO...)

Entity Framework - explain my code

Is this a correct understanding of what this code does - and is it the correct way to update a row which has a URLPath of url so that the IsInProcessing column is true?
I haven't actually tried this code yet. Before I do, I want to try and understand it! It is pieced together from various sources.
The code:
using(var db = new DamoclesEntities())
{
var urls = db.URLS;
var result = urls.FirstOrDefault(u => u.URLPath == url);
result.IsInProcessingQueue = true;
db.SaveChanges();
}
What I think is happening here is within the using I am instantiating the DamoclesEntities() class as var db.
I then instantiate the db.URLS (class / table) to the var urls.
I then find the first row where the URLPath (column) contains url, and that row is assigned to result.
I change that row's IsInProcessingQueue (column value) to true;
Finally, I save the changes to the database.
it is almost correct, but keep in mind, that FirstOrDefault will return null value in case if there is no rows found by specified criteria - URLPath == url.
So in this case next row will produce NullReferenceException.
Just add check of result for a null and do result.IsInProcessingQueue = true;db.SaveChanges(); only if result != null

Getting modified values dynamically

I have got a problem. While updating a row in the table by Linq To Sql,
I want to know the only changed fields.
Suppose I have 25 fields in a page but I only updates 3 fields and at the time of updation, I need to get only those 3 fields, it's old value + it's modified or new value.
Can IT be possible in the Linq To Sql.
I was searching the things on internet and have come to know about DB.GetChangeSet() but it just gives me the modified row.
I have checked other questions related to same from here but I did'nt get the way they were using I also tried but it is giving me error "Sequence contains no elements"
I tried in this way::
where TableClass ObjTbl in the function parameter is the Object containing the new values from the model.
public int UpdateDetails(int Id, TableClass ObjTbl)
{
using (DataContext DB = new DataContext())
{
var Data = DB.TableClass.Where(m => m.PkId == Id).FirstOrDefault();
Data .FirstName = ObjTbl.FirstName;
Data .MiddleInitials = ObjTbl.MiddleInitials;
Data .FkClientID = ObjTbl.FkClientID;
Data .LastName = ObjTbl.LastName;
DB.SubmitChanges();
TableClass instance = DB.GetChangeSet().Updates.OfType<TableClass>().Where(m => m.PkId == Id).First();
DB.TableClass.GetModifiedMembers(instance);
}
}
You need to check for your changes before you call SubmitChanges.
Also, in your example the line
TableClass instance = DB.GetChangeSet().Updates.OfType<TableClass>().Where(m => m.PkId == Id).First();
will throw an exception if nothing was changed, otherwise it will return the record you are amending ie, Data, so you may as well just do something like
ModifiedMemberInfo[] changes = DB.TableClass.GetModifiedMembers(Data);
If nothing has been changed, then this will return an empty array, rather than throw an exception.

C# How do I remove values for a specific item in the database

I'm having problems deleting from my database
I have the following
Member thisMember = db.Members.First(m => m.MemberID == member.MemberID);
db.Members.Remove(thisMember.Name);
db.Members.Remove(thisMember.LastName);
But I keep getting an invalid arguments error. Can someone assist me?
Thanks!
db.Members.Remove is used to remove whole record (row/object) from data source. So you can remove whole member like this:
db.Member.Remove(thisMember);
If you want to set values of thisMember then you can do it like this:
Member thisMember = db.Members.First(m => m.MemberID == member.MemberID);
thisMember.Name = "";
// provided that it allows null value
thisMember.LastName = null;
// save changes in data source
db.SaveChanges();

I can't seem to check a value in a particular column of a datatable. Why?

I have a datatable with data in it (customer addresses). In some instances, column ADDR3 doesn't have a value and column ADDR2 does. I'm attempting to check the value of ADDR3 and if it doesn't contain a value I want to copy the value in ADDR2 to ADDR3 and then blank out ADDR2. I was trying to use the below code, but it isn't working. I placed a breakpoint after my 'if' statement, but the program never breaks. But, I know for a fact that a lot of the rows have null ADDR3 fields. Can anyone tell me what I'm doing wrong?
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
object value = row["ADDR3"];
if (value == DBNull.Value)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}
It's likely that your row["ADDR3"] value is NEVER equal to DbNull.Value. This is often the case with data tables that were transferred over a web service, for example (there will be empty strings instead of nulls due to the XML transformations).
Put a break point BEFORE your if and find exactly what the value is. You might try checking for row["ADDR3"] == null or string.IsNullOrWhiteSpace(row["ADDR3"].ToString())
Have you tried comparing the value to null (rather than DBNull.Value)? I believe DBNull.Value is exclusive for certain database objects and does not appear once read into a dataset/datatable.
Try this:
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
if (
row.IsNull("ADDR3") // True if the value is null
||
String.IsNullOrWhitespace(row["ADDR3"]) // True if the value is "", " ", etc.
)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}

Categories