List(T) from sql db table - c#

I want to create List(T) from sql db table
let's say i have one table
ID Name
1 xyz
2 efd
3 abc
4 pqr
i want to some code in C# who will read this db table data and write
following lines in my c# class or / notepad or whatever...
List<ItemViewModel> Items= new List<ItemViewModel>();
Items.Add(new ItemViewModel() { id= 1, name= "xyz"}
Items.Add(new ItemViewModel() { id= 2, name= "efd"}
Items.Add(new ItemViewModel() { id= 3, name= "abc"}
Items.Add(new ItemViewModel() { id= 4, name= "pqr"}
thanks in advance

Add "dapper" to your project (available on NuGet), then:
var list = connection.Query<YourType>("select * from TableName").ToList();
Or for a parameterless query:
var region = "South";
var list = connection.Query<YourType>(
"select * from TableName where Region=#region", new { region });

Here one of best code that you can got, the following method can deal with any data classes and system defined types :
public List<T> ExecuteQuery<T>(string s, SqlConnection condb, params SqlParameter[] Params)
{
List<T> res = new List<T>();
string er = "";
SqlDataReader r = null;
try {
if (condb == null)
throw new Exception("Connection is NULL");
if (string.IsNullOrEmpty(s))
throw new Exception("The query string is empty");
using (SqlCommand cm = new SqlCommand(s, condb)) {
if (Params.Length > 0) {
cm.Parameters.AddRange(Params);
}
if (cm.Connection.State != ConnectionState.Open)
cm.Connection.Open();
r = cm.ExecuteReader;
object prps = typeof(T).GetProperties;
object prpNames = prps.Select((System.Object f) => f.Name).ToList;
if (r.HasRows) {
while (r.Read) {
if (typeof(T).FullName.Contains("System.")) {
res.Add(r(0));
// Classes
} else {
object c = Activator.CreateInstance(typeof(T));
for (j = 0; j <= r.FieldCount - 1; j++) {
object jj = j;
//er = dt.Rows(jj)("ColumnName").ToLower
object fname = r.GetName(j).ToString;
er = fname;
object fType = r.GetProviderSpecificFieldType(j).ToString.ToLower;
object p = prps.Where((System.Object f) => f.Name.Trim.ToLower == fname.ToLower).ToList;
if (p.Count > 0) {
//Date or DateTime
if (fType.Contains("date")) {
if (!p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value))) {
p(0).SetValue(c, Now, null);
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
//String
} else if (fType.Contains("string")) {
if (r(fname) == null || r(fname).Equals(System.DBNull.Value)) {
p(0).SetValue(c, "", null);
} else {
p(0).SetValue(c, r(fname), null);
}
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
}
}
res.Add(c);
}
}
}
r.Close();
}
//If cm IsNot Nothing Then
// 'cm.Connection.Close()
// cm.Dispose()
//End If
} catch (Exception ex) {
if (r != null && r.IsClosed == false)
r.Close();
throw ex;
}
return res;
}
Usage :
var data = ExecuteQuery<ItemViewModel>("SELECT [ID], [Name] FROM [ItemViewTable]",
new SqlConnection("SomeConnectionString"));

If you just want a list populated with whatever data is currently in the database table, you can just do a simple query. You don't have to involve code generation.
Using linq-to-sql to read the contents of the table and create an ItemViewModel for each entry:
using(var context = new MyLinqDbContext())
{
var items = (from i in context.MyTable
select new ItemViewModel { id = ID, name = Name })
.ToList();
}

If you want C# code generated which is being created from database values and compiled into your solution, you want to use Microsofts text templating engine (T4). To get a hold of this technique, you can read up on it in detail in this blog entry.
If you understand the basics of T4, you can read up this blog, there's an example of how to dynamically create Enum classes for static lookup tables which are stored in a database. Starting from this code, you can write your own code generation template which creates the classes you need.

Related

Object multiple reference IEntityTracker error while saving audit table

first I know this question has been asked but I really couldn't find an answer nor find the root of the problem so maybe a someone points me in the right direction.
I'm having the An entity object cannot be referenced by multiple instances of IEntityChangeTracker. error when trying to save into the log tables.
for the log table, I'm using
https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework
so inside my DbContext class where I define the dbset, I have to override the onscopecreated function
the problem here is that when context.Savechanges run for the first audit record for each table it works but after first record, I get the multiple reference error.
so let's say I have the following tables
Languages table. with the following values
English,French,German
Countries Table with the following values
UK,France,Germany
for languages table, if I change English to English3 and save it works It records to the audit table but then for languages table, I can not do any changes at any records it's the same in every table
what am I missing?
private void SaveToLogTable(AuditScope auditScope)
{
foreach (var entry in ((AuditEventEntityFramework)auditScope.Event).EntityFrameworkEvent.Entries)
{
if(entry.Action is null) return;
if (TABLES.Any(x => x.T_TABLE_NAME.Equals(entry.Table)))
{
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC == entry.Action)?.A_CODE,
LOG_DATE = DateTime.Now,
USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
}
else
{
var table = new TABLES {T_TABLE_NAME = entry.Table};
var newLog = new LOGS
{
LOG_ACTION = ACTIONS.FirstOrDefault(x => x.A_DESC.Equals(entry.Action))?.A_CODE,
LOG_DATE = DateTime.Now,
LOG_USER_REFNO = MyGlobalSettings.MyUser.U_ROWID
//USERS = MyGlobalSettings.MyUser
};
if (entry.Changes != null)
{
foreach (var changes in entry.Changes)
{
var ch = new CHANGES
{
CH_COLUMN = changes.ColumnName,
CH_NEW_VALUE = changes.NewValue.ToString(),
CH_ORIGINAL_VALUE = changes.OriginalValue.ToString()
};
newLog.CHANGES.Add(ch);
}
}
if (entry.ColumnValues != null)
{
foreach (var kv in entry.ColumnValues)
{
var val = new VALUES
{
ColumnName = kv.Key,
ColumnValue = kv.Value is null? "": kv.Value.ToString()
};
newLog.VALUES.Add(val);
}
}
table.LOGS.Add(newLog);
//TABLES.Attach(table);
//TABLES.First(x => x.T_TABLE_NAME.Equals(entry.Table)).LOGS.Add(newLog);
TABLES.Add(table);
//TablesList.Add(table);
}
//entry.Entity
}
}

Fill dropdownlist when there is no data in database

I have a dropdownlist that are filled with age ranging from 0-100. This the user can then choose and the selected value gets inserted into a database via linq. The user doesn't have an age value in the database but this is something that he will add later on the edit page. The problem is that there is an error when loading the "edit profile page" if there is no a NULL value on age in the database.
Error message:
System.NullReferenceException: Object reference not set to an instance of an object. at DatingSite.Members.Redigera.getData(Guid user) in c:\DatingSite\DatingSite\Members\Redigera.aspx.cs:line 43
Code for dropdownlist:
public void addAge()
{
dropAge.Items.Insert(0, "Välj ålder");
int index = 1;
for (int i = 0; i <= 100; i++)
{
ListItem li = new ListItem(i.ToString(), i.ToString());
dropAge.Items.Insert(index, li);
index++;
}
}
Code for getting the users information:
private void getData(Guid user)
{
var repository = new DAL.Repository.UpdateRepository();
currentProfilbild.ImageUrl = "~/" + repository.getAvatar(user);
Fnamn.Text = repository.getName(user);
Enamn.Text = repository.getEnamn(user);
tbxPresText.Text = repository.getPresText(user);
var gender = repository.getGender(user);
try
{
var age = repository.getAge(user).Trim();
if (string.IsNullOrEmpty(age))
{
addAge();
}
else
{
dropAge.SelectedValue = repository.getAge(user).Trim();
}
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
}
Linq-code:
public string getAge(Guid uID)
{
using (var context = new dbEntities())
{
var user = context.UserInformation.First(c => c.UserId == uID);
return user.Ålder;
}
}
The error could be here:
public string getAge(Guid uID)
{
using (var context = new dbEntities())
{
var user = context.UserInformation.First(c => c.UserId == uID);
if(user != null && !String.IsNullOrEmpty(user.Ålder))
return user.Ålder;
else
return string.empty;
}
}
My guess is the exception is here, since the age is null and you're trying to do a Trim operation.
var age = repository.getAge(user).Trim();
May be you can do this.
var age = repository.getAge(user);
if(!string.IsNullOrEmpty(age))
{
age = age.Trim();
}
BTW, you might considering bringing all the data in one call rather than calling multiple times for firstname, lastname, age, etc.

Get ID value from combo box with entity framework

With ADO.net, if I want to retrieve the ID from combobox I just do such like this :
int idToGet = int.parse(tbCategory.SelectedValue.ToString());
Then done,
But when I bind the combobox with EF, it will show error Input string was not in a correct format. So the current value show { id = 7, category = TESTING } and not as usual.
Here a my code snippet :
public void loadCategory()
{
tbCategory.DataSource = null;
var listCategoryObj = new malsic_inventoryEntities();
var query = from cat in listCategoryObj.Category
//join cat in listItmObj.Category on n.id_category equals cat.id
select new { cat.id,cat.category };
if (query.Count() > 0)
{
tbCategory.DataSource = query.ToList();
tbCategory.DisplayMember = "category";
tbCategory.ValueMember = "id";
tbCategory.Invalidate();
}
else
{
tbSubCategory.Enabled = false;
}
}
public void loadSubcategory()
{
tbSubCategory.DataSource = null;
int id_category_current = int.Parse(tbCategory.SelectedItem.Value.ToString());
var listSubCategoryObj = new malsic_inventoryEntities();
var query = from SubCat in listSubCategoryObj.SubCategories
where SubCat.id_category == id_category_current
select new { SubCat.id, SubCat.subcategory };
if (query.Count() > 0)
{
groupBox1.Enabled = true;
tbSubCategory.DataSource = query.ToList();
tbSubCategory.DisplayMember = "subcategory";
tbSubCategory.ValueMember = "id";
tbSubCategory.Invalidate();
}
else
{
groupBox1.Enabled = false;
}
}
I do something wrong?
I don't think your problem is anything to with ADO.NET or Entity Framework. I think your problem is on the line with int.Parse. Try setting id_category_current this way instead of how you do it now:
int id_category_current;
if(!int.TryParse(tbCategory.SelectedItem.Value.ToString(), out id_category_current))
{
groupBox1.Enabled = false;
return;
}

C# Linq Column Name as variable

I have a table where I want to make a query on variable columns.
Like:
private void query(string column, string value) {
using (var db = new myDB()) {
var s1 = (from c in db.Components
where (**column** == **value**)
select new {c.id, **column**});
}
}
lets say I want to look for a supplier then it would be like:
var s1 = (from c in db.Components
where (c.supplier == "abc")
select new {c.id, c.supplier});
is there a way to pass the column name as variable?
This example can be useful i guess.
void BindGridTypeSafe()
{
NorthwindDataContext northwind = new NorthwindDataContext();
var query = from p in northwind.Products
where p.CategoryID == 3 && p.UnitPrice > 3
orderby p.SupplierID
select p;
GridView1.DataSource = query;
GridView1.DataBind();
}
void BindGridDynamic()
{
NorthwindDataContext northwind = new NorthwindDataContext();
var query = northwind.Products
.Where("CategoryID = 3 AND UnitPrice > 3")
.OrderBy("SupplierID");
GridView1.DataSource = query;
GridView1.DataBind();
}
A nice way is to use Dynamic Linq
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Something like:
var s1 = (from c in db.Components
where(column + "=" + value)
select new {c.id, **column**});
Short answer is to add library System.Linq.Dynamic as a reference and do:
string columnName = "Supplier";
var s1 = Suppliers
.Where(String.Format("{0} == \"abc\"", columnName))
.Select(new {c.id, c.supplier};
Following is a complete working example of Dynamic Linq, where column-name is a parameter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
public class Program
{
public static void Main()
{
var lstContacts = new List<Contact>{
new Contact{Id = 1, Active = true, Name = "Chris"},
new Contact{Id = 2, Active = true, Name = "Scott"},
new Contact{Id = 3, Active = true, Name = "Mark"},
new Contact{Id = 4, Active = false, Name = "Alan"}};
string columnName = "Active";
List<Contact> results = lstContacts.Where(String.Format("{0} == true", columnName)).ToList();
foreach (var item in results)
{
Console.WriteLine(item.Id.ToString() + " - " + item.Name.ToString());
}
}
}
public class Contact
{
public int Id
{
get;
set;
}
public bool Active
{
get;
set;
}
public string Name
{
get;
set;
}
}
You can experiment with this .net-fiddle-here
I'm resurrecting this old thread because I had to work around that issue with ASP.NET Core 2.2 today. I used the System.Linq.Dynamic.Core NuGet package to create the following extension method, which works beautifully if you need to check if multiple given string values are contained within multiple given columns.
public static IQueryable<TEntity> WhereContains<TEntity>(
this IQueryable<TEntity> query,
string field,
string value,
bool throwExceptionIfNoProperty = false,
bool throwExceptionIfNoType = false)
where TEntity : class
{
PropertyInfo propertyInfo = typeof(TEntity).GetProperty(field);
if (propertyInfo != null)
{
var typeCode = Type.GetTypeCode(propertyInfo.PropertyType);
switch (typeCode)
{
case TypeCode.String:
return query.Where(String.Format("{0}.Contains(#0)", field), value);
case TypeCode.Boolean:
var boolValue = (value != null
&& (value == "1" || value.ToLower() == "true"))
? true
: false;
return query.Where(String.Format("{0} == #0", field), boolValue);
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return query.Where(String.Format("{0}.ToString().Contains(#0)", field), value);
// todo: DateTime, float, double, decimals, and other types.
default:
if (throwExceptionIfNoType)
throw new NotSupportedException(String.Format("Type '{0}' not supported.", typeCode));
break;
}
}
else
{
if (throwExceptionIfNoProperty)
throw new NotSupportedException(String.Format("Property '{0}' not found.", propertyInfo.Name));
}
return query;
}
The code can be used with .NETStandard/.NETCore (using the aforementioned System.Linq.Dynamic.Core package) and also with ASP.NET 4.x (using the System.Linq.Dynamic package).
For further info regarding the WhereContains extension method and a full use-case info, check out this post on my blog.

What can be used instead of Datatable in LINQ

I have a SQL query that returns a Datatable:
var routesTable = _dbhelper.Select("SELECT [RouteId],[UserId],[SourceName],[CreationTime] FROM [Routes] WHERE UserId=#UserId AND RouteId=#RouteId", inputParams);
and then we can work with Datatable object of routesTable
if (routesTable.Rows.Count == 1)
{
result = new Route(routeId)
{
Name = (string)routesTable.Rows[0]["SourceName"],
Time = routesTable.Rows[0]["CreationTime"] is DBNull ? new DateTime() : Convert.ToDateTime(routesTable.Rows[0]["CreationTime"])
};
result.TrackPoints = GetTrackPointsForRoute(routeId);
}
I want to change this code to linq but I don't know how can I simulate Datatable in LINQ ,I wrote this part:
Route result = null;
aspnetdbDataContext aspdb = new aspnetdbDataContext();
var Result = from r in aspdb.RouteLinqs
where r.UserId == userId && r.RouteId==routeId
select r;
....
but I don't know how can I change this part:
if (routesTable.Rows.Count == 1)
{
result = new Route(routeId)
{
Name = (string)routesTable.Rows[0]["SourceName"],
Time = routesTable.Rows[0]["CreationTime"] is DBNull ? new DateTime() : Convert.ToDateTime(routesTable.Rows[0]["CreationTime"])
};
would you please tell me how can I do this?
EDIT
here you can see the whole block of code in original
public Route GetById(int routeId, Guid userId)
{
Route result = null;
var inputParams = new Dictionary<string, object>
{
{"UserId", userId},
{"RouteId", routeId}
};
var routesTable = _dbhelper.Select("SELECT [RouteId],[UserId],[SourceName],[CreationTime] FROM [Routes] WHERE UserId=#UserId AND RouteId=#RouteId", inputParams);
if (routesTable.Rows.Count == 1)
{
result = new Route(routeId)
{
Name = (string)routesTable.Rows[0]["SourceName"],
Time = routesTable.Rows[0]["CreationTime"] is DBNull ? new DateTime() : Convert.ToDateTime(routesTable.Rows[0]["CreationTime"])
};
result.TrackPoints = GetTrackPointsForRoute(routeId);
}
return result;
}
SELECT Function:
public DataTable Select(string query, Dictionary<string, object> parameters)
{
var dt = new DataTable();
using (_command = new SqlCommand(query, _connnection))
{
InitializeParametersAndConnection(parameters);
using (_adapter = new SqlDataAdapter(_command))
{
_adapter.Fill(dt);
}
}
return dt;
}
and the GetTrackPointsForRoute
private List<TrackPoint> GetTrackPointsForRoute(int routeId)
{
aspnetdbDataContext aspdb = new aspnetdbDataContext();
var result = new List<TrackPoint>();
var trackPointsTable = from t in aspdb.TrackPointlinqs
where t.RouteFK == routeId
select t;
foreach (var trackPointRow in trackPointsTable)
{
var trackPoint = new TrackPoint
{
Id = (int)trackPointRow.TrackPointId,
Elevation = Convert.ToSingle(trackPointRow.Elevation),
Latitude = Convert.ToDouble(trackPointRow.Latitude),
Longitude = Convert.ToDouble(trackPointRow.Longitude),
Time = trackPointRow.TrackTime is DBNull ? new DateTime() : (DateTime)trackPointRow.TrackTime
};
result.Add(trackPoint);
}
return result;
}
var firstRoute = aspdb.RouteLinqs
.Where(r => r.UserId == userId && r.RouteId == routeId)
.FirstOrDefault();
if (firstRoute == null)
{
return null;
}
else
{
return new Route(routeId)
{
Name = first.SourceName,
Time = first.CreationTime ?? new DateTime(),
TrackPoints = GetTrackPointsForRoute(routeId)
};
}
If this is LINQ to SQL you can simplify it further (this won't work with LINQ to Entity Framework though):
return aspdb.RouteLinqs
.Where(r => r.UserId == userId && r.RouteId == routeId)
.Select(r => new Route(routeId)
{
Name = r.SourceName,
Time = r.CreationTime ?? new DateTime(),
TrackPoints = GetTrackPointsForRoute(routeId)
})
.FirstOrDefault();
Note: You probably can replace GetTrackPointsForRoute with a join to the child table, meaning that the entire method can be done with a single call to the database, rather than one call to get the routes, and a second call to get the points. To do this you should learn about associations and joins in LINQ to SQL.

Categories