Linq to entity delete a specific column from a table - asp.net

Linq to entity query to delete a specific column from a table by matching a condition`
public ActionResult deleteChecks(string checkValue)
{
check_master checks = (from table in db.check_master
where table.check_code == checkValue
select table).First();
//now how to delete/remove checks.mcheck
return View("Edit");
}`
Only want to update a single column element with null value(of selected row) from the table check_master

You can set a single property (which maps to a column) to null and save it to the database
foreach(check_master check in checks)
{
check.mcheck = null;
}
db.SaveChanges();

using (NorthwindDataContext db = new NorthwindDataContext())
{
// Retrieve the existing entity. Database Call 1
Product product = db.Products.First(p => p.ProductID == 1);
// Change the properties. LINQ to SQL knows
// these specific properties have changed.
product.UnitsInStock = 14;
// Flush the changes. Database Call 2
db.SubmitChanges();
}

Entity framework works with constant table scheme only.
Tell please, what your global aim is, may be there's some more suitable way to do it.
Updated:
foreach(var chm in db.check_master)
{
chm.mcheck = null;
}
db.SaveChanges();

I believe that Linq to Entities only support DML, it does not support DDL operations.
So you would have to use stored procedure or ADO.NET raw query.
EDIT
you can do simple update like this :
public ActionResult deleteChecks(string checkValue)
{
check_master checks = (from table in db.check_master
where table.check_code == checkValue
select table).First();
checks.mcheck = null;
db.SaveChanges();
return View("Edit");
}`

Related

Removing item from list in EF model

I'm using Entity Framework and I am trying to remove a NinjqEquiment from a list belonging to an instance of Ninja.When I retrieve the list of Ninjas,I make sure to include the equipment list, so I know they are there. Then I remove the equipment from the Ninja and try to save changes. I get the following error -
The entity type List`1 is not part of the model for the current
context.
using (var db = new NinjaDbContext())
{
//get ninjas with equipment included
var ninjas = GetAllNinjas();
//get ninja
var ninja = (from n in ninjas
where n.Id == id
select n).FirstOrDefault();
//get equipment
var eq = (from e in ninja.EquipmentOwned
where e.Id == removeEqId
select e).FirstOrDefault();
//remove eq from ninja
ninja.EquipmentOwned.Remove(eq);
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
//save ninja
db.SaveChanges();
}
Just remove this:
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
This causes the error.
EquipmentOwned is a List<Equipment>. It is not an Entry in EF terms so it is not tracked directly by it.
When you delete an entity from such collection, EF knows that there won't be any relationship between this particular ninja and this particular equipment. It won't delete equipment from database because other ninjas may use this equipment.
To delete it completely you should remove this equipment from corresponding DbSet<> like this:
using (var db = new NinjaContext())
{
//db.Equipment is a DbSet<Equipment>
//id is PrimaryKey of Equipment table
var eq = db.Equipment.Find(id);
db.Equipment.Remove(eq);
db.SaveChanges();
}

Query to fetch table names from AX takes too long

I am using the following code in X++ to get table names:
client server public static container tableNames()
{
tableId tableId;
int tablecounter;
Dictionary dict = new Dictionary();
container tableNamesList;
for (tablecounter=1; tablecounter<=dict.tableCnt(); tablecounter++)
{
tableId = dict.tableCnt2Id(tablecounter);
tableNamesList = conIns(tableNamesList,1,dict.tableName(tableId));
}
return tableNamesList;
}
Business connector code :
tablesList = (AxaptaContainer)Global.ax.
CallStaticClassMethod("Code_Generator", "tableNames");
for (int i = 1; i <= tablesList.Count; i++)
{
tableName = tablesList.get_Item(i).ToString();
tables.Add(tableName);
}
The application hangs for 2 - 3 minutes while fetching data. What could be the cause? Any optimizations?
Rather than use ConIns, use +=, it will be faster
tableNamesList += dict.tableName(tableId);
ConIns has to work out where in the container to place the insert. += just adds it to the end
As mentioned before avoid conIns() when appending elements to a container because it makes a new copy of the container. Use += instead to append in place.
Also, you may want to check for permissions and leave out temporary tables, table maps, and other special cases. Standard Ax has a method to build a table name lookup form that takes these things into account. Check the method Global::pickTable() for details.
You could avoid some calls through the business connector as well and build the entire list in Ax in a similar way and return that in a single function call.
If you are using Dynamics Ax 2012, you could skip the treeNode stuff and use the SysModelElement table to fetch the data and return it immediately as a .Net Array to easy up things on the other side.
public static System.Collections.ArrayList FetchTableNames_ModelElementTables()
{
SysModelElement element;
SysModelElementType elementType;
System.Collections.ArrayList tableNames = new System.Collections.ArrayList();
;
// The SysModelElementType table contains the element types
// and we need the recId for the next selection
select firstonly RecId
from elementType
where elementType.Name == 'Table';
// With the recId of the table element type,
// select all of the elements with that type (hence, select all of the tables)
while select Name
from element
where element.ElementType == elementType.RecId
{
tableNames.Add(element.Name);
}
return tableNames;
}
}
Alright, I have tried a lot of things and in the end, I decided to create a table consisting of all table names. This table will have a Job populating it. I am fetching records from this table.

in asp.net dynamic date, how to use partial method to validate fields aganist data in database

i want to make sure all product names are unique so i tried to do the following.
but it is causing an infinity loop at the lambda expression.
public partial class Product
{
partial void OnProductNameChanging(string value)
{
using(var ctx = new MyEntityContext()){
var val = value;
var item = ctx.Products.Where(o=>o.ProductName == val).FirstOrDefault();
if(item != null)
throw new ValidationException("Product Name existed.");
}
}
}
i'm using asp.net 4.0 with dynamic data and entity framework.
Why don't you set it up on database level and handle exeption in case if product name already exists?
I am not too familiar with EF, but you should get the changeset and compare values. That is, for the Product Entity and in the case of the the changeset having an Update, compare the EXISTING value with NEW, and change the new in the case of duplication.
Here's how to get changeSet in EF :
http://davidhayden.com/blog/dave/archive/2005/11/16/2570.aspx
the comparison and value must be called before any context.SubmitChanges();
Hope this helps.

How to delete in linq to sql?

I am very new to linq to sql and I am not sure how to actually delete a record.
So I been looking at this tutorial
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
So for Update they have
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.Single(p => p.ProductName == "Toy 1");
product.UnitPrice == 99;
product.UnitsInStock = 5;
db.SubmitChanges();
For delete they have
NorthwindDataContext db = new NorthwindDataContext();
var toyProducts = from p in db.Producsts
where p.ProductName.Contains("Toy")
select p;
db.Products.RemoveAll(toyProducts);
db.SubmitChanges();
So do I have to query every time, to get the record in order to delete that record? Like I can sort of see doing this with update since you need to give it a record which to update first and then make the changes so I understand the querying part but not with delete.
Like can't you just send in what you want to delete and it goes and deletes it? why do you have to first get it and then tell it to be deleted?
Is that not 2 hits on the database?
Also I have foreign key relationship that I am trying to get to work. So I have this
public ViewResult(string param1, string param2)
{
Table A = new Table A
A.Field1 = param1;
A.Field2 = param2;
Delete(A);
}
private void Delete(Table A)
{
DbContext.A.DeleteAllOnsubmit(A.TableB);
DbContext.A.DeleteAllOnSubmit(A.TableC);
DbContext.A.DeleteOnSubmit(A);
}
So this fails it comes up with this message "Cannot remove an entity that has not been attached."
So I can see why the first 2 lines would fail in the delete method, since I made a new object and their is nothing in the object that has any information about TableB and TableC.
I however can't see why the last line still fails even if the 2 other lines where not there.
Like how I thought it would work it would take my Table A class object that I passed in and look through the table for that information contained in it. It does not seem to be the case though.
So do I first have to take the information out and then do a query to get it and then delete it, like in the example?
Also what is the difference between removeAll() and say DeleteAllOnSubmit().
Like I said I am new to linq to sql and have not been able to sit down and read a book on it due to time constraints. Once I have more time I will read through a book probably.
Thanks
You have several questions in your one question, but I will start with the simplest, about attaching, if you already have the primary key. If you don't have the primary key then I have always just done a fetch then a delete, but, whenever I do a fetch I tend to store the primary key for updates and deletes.
It will delete off of the primary key, but if you have that then just attach as I do below and call delete. I don't pass around the object needed by DLINQ as I want to be able to change it if I want, so I pass in a different User object and just pull the PK from the business class and put it into the DAO class.
var db = new MeatRequestDataContext();
if (input.UserID > 0)
{
entity = new User()
{
UserID = input.UserID
};
db.Users.Attach(entity);
db.Users.DeleteOnSubmit(entity);
}
this is a simple way to delete row from table by linq query.may be it helps .
var summary_delete = database.summeries.Find(id);
var delete = database.summeries.Remove(summary_delete);
database.SaveChanges();
reference : http://mvc4asp.blogspot.in/2013/09/how-to-delete-table-row-in-sql-database.html
Inserted_LINQDataContext db = new Inserted_LINQDataContext();
Item itm = new Item();
int ID = Convert.ToInt32(TextBox1.Text);
var DeleteID = from d in db.Items
where d.id == ID
select d;
db.Items.DeleteAllOnSubmit(DeleteID);
db.SubmitChanges();
Label2.Text = "Record deleted Successfully.";
TextBox1.Text = "";
where Item is Table name, Linserted_LINQDataContext is your Linq DB name, id is the Column name in Item table. Items is the alias name of Item table in linq.
SupportDataDataContext Retrive = new SupportDataDataContext();
// SupportDataDataContext delete = new SupportDataDataContext();
Topic res = Retrive.GetTable<Topic>().Single(t => t.ID == topicID);
if (res != null)
{
Retrive.Topics.DeleteOnSubmit(res);
Retrive.SubmitChanges(ConflictMode.ContinueOnConflict);
}
I know the question is old but this may be useful to someone:
"YourDataContext" dc = new "yourDataContext";
"YourTable" element = dc."YourTable".First(a => a.Id == 12345);
dc."YourTable".DeleteOnSubmit(element);
dc.SubmitChanges();

Issue with LINQ to SQL insert . .

i was looking at an example of how to do an insert in Linq to SQL and here it was it said:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.Add(new Product(..));
context.SubmitChanges();
but when i look at the below, (in my case the Table is UserInfo), the Table doesn't have an "Add" method:
public System.Data.Linq.Table<UserInfo> UserInfos
{
get
{
return this.GetTable<UserInfo>();
}
}
any clue what i am doing wrong here?
You should use the InsertOnSubmit method:
NorthwindDataContext context = new NorthwindDataContext();
context.Products.InsertOnSubmit(new Product(..));
context.SubmitChanges();
The Add method exist on the EntitySet members, is mostly used when adding Child entities to a Parent one, for example:
var category = new Category{ Name = "Breveages"};
category.Products.Add(new Product{ Name = "Orange Juice"});
category.Products.Add(new Product{ Name = "Tomato Juice"});
category.Products.Add(new Product{ Name = "Cola"});
//...
context.Categories.InsertOnSubmit(category);
// This will insert the Category and
// the three Products we associated to.
EDIT: To do update operations, you just need to retrieve the entity by doing a query, or attaching it, for example:
var customer = context.Customers.Single( c => c.CustomerID == "ALFKI");
customer.ContactName = "New Contact Name";
context.SubmitChanges();
The DataContext tracks the changes of its related entities and when the SubmitChanges method is called, it will detect that change, and generate an Update SQL statement behind the scenes to do the update operation...

Resources