I get data from my database with this code
var table = kantarDataSetTartimlarTableAdapter.GetData().Select(s => new
{
s.DateColumn,
s.Index
}).AsEnumerable().Select ((s, column) => new
{
s.DateColumn,
s.Index
column_no = column + 1
});
If date column is not null I haven't got any problem. But when date column have null data I have a problem:
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public System.DateTime event_start_date {
get {
try {
return ((global::System.DateTime)(this[this.tableDataTable1.event_start_dateColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'event_start_date\' in table \'DataTable1\' is DBNull.", e);
}
}
set {
this[this.tableDataTable1.event_start_dateColumn] = value;
}
}
How can I solve this error?
It appears your DB column & entity model are out of sync. If you are getting a null value back from the database then that field must be nullable. For that to map across to your model it must also support nullable dates.
You need to update event_start_date in your model to use Nullable<DateTime>/DateTime?.
You may try providing a default value when reading the value from your database to ensure you aren't storing any nulls:
DateColumn = s.DateColumn ?? DateTime.MinValue
I update event_start_date and I solve my problem
get {
try {
if (this[this.table.DateTimeColumn] is DBNull)
{
return Convert.ToDateTime(null);
}
else
{
return ((global::System.DateTime)(this[this.table.DateTimeColumn]));
}
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("Description", e);
}
}
set {
this[this.table.DateTimeColumn] = value;
}
Related
I have this Service that works to delete one (1) row from the database (Sorry for any lingo errors.):
public bool DeleteSchedulesFromDate(DateTime objDateTime)
{
var result = _db.Schedules.FirstOrDefault(x => x.AppointmentDateEnd <= objDateTime);
if (result != null)
{
_db.Schedules.Remove(result);
_db.SaveChanges();
}
else
{
return false;
}
return true;
}
This as the calling function:
private void DeleteSchedules(string dtEnd)
{
deleteScheduleDate = dtEnd;
DateTime _dtEnd;
if (DateTime.TryParse(dtEnd, out _dtEnd))
{
var result = #Service.DeleteSchedulesFromDate(_dtEnd);
schedules.Clear();
schedules = Service.GetSchedules();
if (result)
{
this.ShouldRender();
}
}
}
But how do I change it to delete all rows that matches the passed DateTime object?
I have tried :
to change it to a List, but then the bool doesn't work.
set a loop in the Service, but can't make it run correctly.
set a loop in the function call, but can't make it work either.
to google and look up other posts on SO, but found no match.
Instead of searching for the first match with FirstOrDefault you should get all valid result into a List (Where + ToList) and delete all of them (RemoveRange)
var result = _db.Schedules.Where(x => x.AppointmentDateEnd <= objDateTime).ToList();
if (result.Any())
{
_db.Schedules.RemoveRange(result);
_db.SaveChanges();
}
Please consider this scenario:
I have two tables: Temp and Convert. The structure of these 2 tables are exactly same. I want to do some operation on each record of Temp and add it to Convert table. By doing my work, there may be duplicate records in Convert table and so I don't want to insert that record in Convert table. I wrote this code:
foreach (var item in allRecords)
{
var converted = new Convert()
{
F1 = item.F1,
F2 = item.F2,
F3 = DoWork(F3),
};
try
{
context.Convert.AddObject(converted);
context.SaveChanges();
}
catch (Exception ex)
{
var msg = "Violation of PRIMARY KEY constraint 'PK_Convert'."
+ " Cannot insert duplicate key":
if (ex.InnerException.Message.Contains(msg))
{
continue;
}
else
{
throw ex;
}
}
}
the problem is when I get exception for first duplicate and continue command executed, it seems that duplicate record not discard and still wait for save. After first exceptionÙˆ No record is stored in the database because of my first duplicate error. How I can solve this issue without checking existence of duplicate error in Convert table?
Thanks
You can try to check if the entity exists and if not - add it? Like this :
using System.Linq.Expressions;
public class ContextWithExtensionExample
{
public void DoSomeContextWork(DbContext context)
{
var uni = new Unicorn();
context.Set<Unicorn>().AddIfNotExists(uni , x => x.Name == "James");
}
}
public static class DbSetExtensions
{
public static T AddIfNotExists<T>(this DbSet<T> dbSet, T entity, Expression<Func<T, bool>> predicate = null) where T : class, new()
{
var exists = predicate != null ? dbSet.Any(predicate) : dbSet.Any();
return !exists ? dbSet.Add(entity) : null;
}
}
You can use this method directly and remember to call DbContext.SaveChanges() after the call.
var converted = new Convert()
{
F1 = item.F1,
F2 = item.F2,
F3 = DoWork(F3),
};
As F3 is your primarykey, then just check if it exists before inserting:
if(context.Convert.Any(x => x.F3 == converted.F3)
{
//deal with the error
}
else
{
context.Convert.AddObject(converted);
context.SaveChanges();
}
I am reading rows from a table in SQL Server using C# in SSIS. As I loop through each column I want to get the datatype of the field from the table. Here is my code:
string s = "";
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\cassf\Documents\Tyler Tech\FL\ncc3\CM_Property.csv", true))
{
foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
{
if (!inputColumn.Name.EndsWith("IsNull"))
{
try
{
s += Convert.ToString(inputColumn.GetValue(Row,null).ToString());
}
catch
{
some code
}
}
}
}
}
First issue is when I do the Convert.ToString() on a Bit field from the database, it changes the value to either True or False. I want the actual value of 1 or 0.
So to try and fix this I want to check the field type for Boolean, it appears that the script is converting from a bit to boolean. Then I can manually put the 1 or 0 back. I would prefer to have the value directly from the database though.
Any help would be greatly appreciated.
Thanks,
Kent
I'd implement a helper function to make your own conversion, when needed, like this:
string s = "";
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\cassf\Documents\Tyler Tech\FL\ncc3\CM_Property.csv", true))
{
foreach (PropertyInfo inputColumn in Row.GetType().GetProperties())
{
if (!inputColumn.Name.EndsWith("IsNull"))
{
try
{
s += ValueToString(inputColumn.GetValue(Row,null));
}
catch
{
some code
}
}
}
}
}
protected string ValueToString(object value)
{
if (value == null)
throw new ArgumentNullException("I don't know how to convert null to string, implement me!");
switch (Type.GetTypeCode(value.GetType()))
{
// Any kind of special treatment, you implement here...
case TypeCode.Boolean: return Convert.ToInt16(value).ToString();
default: return value.ToString(); // ...otherwise, just use the common conversion
}
}
For booleans, you just convert it to Int, and the int to string (you'll get 1 or 0 in string format).
Depending on what you're going to do with the s variable, you might want to surround string values with quotes, if so, you could do it inside ValueToString() method.
I'm having an issue when trying to update a value on my database and can't really find much if any help through Google.
I want to set a column called IsOpen (bool but because of SQLite I'm using integer) to 0 (false) if the EndDate for this entry is today (now). When I run my UPDATE query I get the following exception; "Cannot update List1: it has no PK".
I don't understand this because I've checked my Model class and I clearly have a PK set;
[SQLite.AutoIncrement, SQLite.PrimaryKey]
public int GoalID
{
get { return _goalID; }
set
{
if (_goalID != value)
_goalID = value;
OnPropertyChanged("GoalID");
}
}
I'm attempting to update this way;
string sql = #"UPDATE GoalsTrackerModel
SET IsOpen = '0'
WHERE EndDate = datetime('now')"; // I've also tried date('now')
_dbHelper.Update<GoalsTrackerModel>(sql);
My Update<> looks like;
public void Update<T>(string stmt) where T : new()
{
using (var conn = new SQLiteConnection(App.ConnectionString))
{
var result = conn.Query<T>(stmt);
if (result != null)
{
conn.RunInTransaction(() =>
{
conn.Update(result);
});
}
}
}
But like I said, I keep getting "Cannot update List1: it has no PK". What's throwing me off as well is if I change the WHERE to something like; WHERE IsOpen = '1' then it'll update all the values that have 1 to 0, but it'll still give me the "Cannot update List1: it has no PK" message.
Maybe my WHERE is wrong when checking if the EndDate = now? I'm implementing all this as soon as the page is opened. Any ideas?
Thanks.
"[SQLite.AutoIncrement, SQLite.PrimaryKey]" is C# code, not SQL code. Just because you've defined in C# what your primary key is, doesn't mean the SQLite table is really defined that way. You'll need to look at the table itself as it is defined within SQLite to fix that.
My Update method was causing the problem. Changed it and started using SQLiteCommand and ExecuteNonQuery instead of the SQLiteConnection's Update().
In case it helps anyone in the future, here's my new update method;
public void Update<T>(string stmt, string table) where T : new()
{
using (var conn = new SQLiteConnection(App.ConnectionString))
{
var result = conn.Query<T>("SELECT * FROM " + table);
if (result != null)
{
conn.RunInTransaction(() =>
{
SQLiteCommand cmd = conn.CreateCommand(stmt);
cmd.ExecuteNonQuery();
});
}
}
}
I need to create a "common" grid with parameters.
The problem is that in the Delete action I cannot refer to the table as a variable
I use edmx model.
public ActionResult PartialView_GridCommonDelete(System.Int64 data_autoinc)
{
var table = ViewBag.CurrentTable;
var key= ViewBag.Key;
if (data_autoinc != null)
{
try
{
//ERROR HERE
var item = **ent.table**.FirstOrDefault(it => it.product_autoinc == data_autoinc);
if (item != null)
ent.tabla.Remove(item);
ent.SaveChanges();
}
catch (Exception e)
{
ViewData["EditError"] = e.Message;
}
}
return PartialView("PartialView_GridCommon", ViewBag.CurrentSql);
}
How can I dynamically substitute the table name so as I can use it with many tables?
Thank you
What you are trying to do is not achievable by ORM i.e. defining Table at runtime.
What you can try is:
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
You can explicitly pass table name and fire your sql query
Give it a try.
Thanks
Nipun