ADO.NET DataRow - check for column existence - datatable

How do I check for the existence of a column in a datarow?
I'm building datatables to organize some data that I've already pulled back from the database. Depending on the type of data in each row, I need to create a datatable with different columns. Then, later on, I want to check and see if the datatable I am looking at has a certain column.
I know I can catch the exception and handle it that way, but I'm curious if there is a property or method on the datarow object that will do this for me?
Here's how I can do it by catching the exception:
public static String CheckEmptyDataRowItem(DataRow row, String rowName, String nullValue)
{
try
{
return row[rowName].ToString();
}
catch (System.ArgumentException)
{
return nullValue;
}
}

You can simply check like this:
return row.Table.Columns.Contains(columnName);

DataTables have that schema info, so check if the Row's Table's Columns collection contains the field.

Related

Get record real value after overriding it

I've overridden a a record value like the following :
public function getWeightAttribute($weight)
{
if($weight)
{
return $weight;
}
return 70;
}
Now I have a collection of that model and I want to know if the original value was null or not.
I want to do it without connecting to DB again, Actually I want to make sure the user has filled the weight and some other fields while registering.
Some sections are working based on the above override and I don't want to mess them up neither use extra connections to db.
Thanks In Advance,
In order to get the original value, you can use:-
$fetchData->getAttributes()['weight'];

How can I delete all records from a table?

I've been searching for an answer on how to delete ALL records from a table using LINQ method syntax but all answers do it based on an attribute.
I want to delete every single record from the databse.
The table looks like so:
public class Inventory
{
public int InventoryId { get; set; }
public string InventoryName { get; set; }
}
I'm not looking to delete records based on a specific name or id.
I want to delete ALL recods.
LINQ method syntax isn't a must, bt I do prefer it since it's easier to read.
To delete all data from DB table I recommend to use SQL:
Trancate Table <tableName>
Linq is not meant to change the source. There are no LINQ methods to delete or update any element from your input.
The only method to change you input, is to select the (identifiers of the )data that you want to delete in some collection, and then delete the items one by one in a foreach. It might be that your interface with the source collection already has a DeleteRange, in that case you don't have to do the foreach.
Alas you didn't mention what your table was: Is it a System.Data.DataTable? Or maybe an Entity Framework DbSet<...>? Any other commonly used class that represents a Table?
If you table class is a System.Data.DataTable, or implements ICollection, it should have a method Clear.
If your tabls is an entity framework DbSet<...>, then it depends on your Provider (the database management system that you use) whether you can use `Clear'. Usually you need to do the following:
using (var dbContext = new MyDbContext(...))
{
List<...> itemsToDelete = dbContext.MyTable.Where(...).ToList();
dbContext.MyTable.RemoveRange(itemsToDelete);
dbContext.SaveChanges();
}

How to check id which I used from a table that related with other multiple table?

When I want to delete a row from table I want to check the tables which use the id of this row. If used then it doesn't allow to delete.
You can simply check whether specific column(containing other table's key) in the row is empty or null and if it is empty then delete the row otherwise skip it.
You have two ways in which you can do it-
using eloquent get the row by primary key and check the property on collection.
write a stored procedure in the database and call it in your Laravel code.
You can use the deleting model event to check if the relationships exist. If they do, then prevent the delete.
https://laravel.com/docs/5.7/eloquent#events
If you create an observer for your model, you can use something like this:
public function deleting($model)
{
if($model->someRelation->count()) { // replace ->someRelation with whatever you want to check
return false; // prevent delete
}
if($model->anotherRelation->count()) {
return false; // prevent delete
}
}

Unable to retrieve Dictionary value when used in LINQ

I am trying to update a 'Name' DataColumn based on a 'ID' DataColumn in a DataTable.
The 'ID'-'Name' pairs are stored in a Dictionary, which is created using a DataTable extension method as follows:
public static Dictionary<object, object> ToDictionary(this DataTable dataTable, string keyColumn, string valueColumn)
{
Dictionary<object, object> resultDict = new Dictionary<object, object>();
if (dataTable.Columns.Contains(keyColumn) && dataTable.Columns.Contains(valueColumn))
{
foreach (DataRow dr in dataTable.Rows)
if (resultDict.ContainsKey(dr[keyColumn]) == false)
resultDict.Add(dr[keyColumn], dr[valueColumn]);
}
return resultDict;
}
I am using the following LINQ syntax to update the DataColumn:
misUserDetailsDT.AsEnumerable().ToList().ForEach(row => row.SetField("DepartmentName", deptDict[row["DepartmentID"]].ToString()));
Here 'misUserDetailsDT' is the DataTable containing a filled column 'DepartmentID' and an empty column 'DepartmentName'-which I am trying to update.
I have a seperate method which generates the Dictionary as follows:
var deptDict = departmentDT.ToDictionary("DeptID", "DeptName");
where 'departmentDT' is a DataTable containing columns 'DeptID' and 'DeptName'.
Now when I execute the Linq code it give a 'KeyNotFoundException'. I have thoroughly checked that the 'departmentDT' table as well as 'deptDict' have all the keys(departmentIDs) from the 'misUserDetailsDT' table. Actually the 'departmentDT' itself has been generated from all the distinct IDs of 'misUserDetailsDT' table.
I think there is some issue with figuring out the appropriate type of the Dictionary keys. I even tried casting it to Int16, but it didn't work out.
Please help me figure out a solution.
I have figured out the problem. The code works when dictionary values are casted to Int32. Thanks to #TimSchmelter for giving a very useful info. I will be changing the code to make use of foreach loop instead.

Use session as source of field for dynamic data column

I have a Dynamic Data column that I want to be populated by a field from the Session collection. (So that when the user chooses to manipulate data related to that column, where necessary, they will see information based on that field, which is stored in session).
Is there an attribute I need to use, or create?
I have had success creating an extended property in the metadata :
public partial class MyTable
{
[ScaffoldColumn(true)]
public string MyValueFromSession
{
get
{
return Session["theAttribute"].ToString();
}
}
}
then you can specify a new column called MyValueFromSession in the MyTable metadata.
Hope this helps.

Resources