I have a table that has a smalldatetime NOT NULL field with a default value of getdate(). When creating a new record in the table, I don't set the smalldatetime field in code through LINQ To SQL syntax, I just let the database set the default value which is the current date. If I don't explicitly set it in code, it throws the following error:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
If I am setting a default in the database, why should I have to set it in code? I have noticed funky things with dates when it comes to LINQ To SQL.
Rather than setting the field as IsDbGenerated, you may want to consider setting its AutoSync value to OnInsert. IsDbGenerated won't let you set the field's value ever (which may be what you want for a "created date" field, but not for a "last modified" field).
However, if you're using an ORM, I would ask you to consider whether you want your application logic in both the database and the application code. Does it make more sense to implement the default value in code (via partial methods like Insert[Entity])?
You have to set the generated property so that LINQ to SQL doesn't send its default value along for creation.
The property is called "Auto Generated Value" on the entity.
To get around this, ensure that your LINQ To SQL model knows that your smalldatetime field is auto-generated by the database.
Select the table's field in your LINQ To SQL diagram, and find the Properties window. Adjust the Auto Generated Value property to True. This will ensure that the field IS NOT included in the INSERT statement generated by LINQ To SQL.
Alternately, you'd have to specify this yourself:
if (newCustomer.DateTimeCreated == null) {
newCustomer.DateTimeCreated = DateTime.Now; // or UtcNow
}
LINQ To SQL does not observe database defaults in a way that you can then subsequently update the value. In order to allow this, you need to set default values in your code.
When creating new objects that are NOT NULL with a database default, C# will use default values, such as MinValue for numbers and dates, empty GUIDs (zeros), etc. You can look for these conditions and replace with your own default value.
This is a known design issue with LINQ To SQL. For an in-depth discussion, see this link:
http://www.codeproject.com/KB/linq/SettingDefaultValues.aspx
Some example code for setting default values in your application:
private void SetDefaults(object LinqObj)
{
// get the properties of the LINQ Object
PropertyInfo[] props = LinqObj.GetType().GetProperties();
// iterate through each property of the class
foreach (PropertyInfo prop in props)
{
// attempt to discover any metadata relating to underlying data columns
try
{
// get any column attributes created by the Linq designer
object[] customAttributes = prop.GetCustomAttributes
(typeof(System.Data.Linq.Mapping.ColumnAttribute), false);
// if the property has an attribute letting us know that
// the underlying column data cannot be null
if (((System.Data.Linq.Mapping.ColumnAttribute)
(customAttributes[0])).DbType.ToLower().IndexOf("not null") != -1)
{
// if the current property is null or Linq has set a date time
// to its default '01/01/0001 00:00:00'
if (prop.GetValue(LinqObj, null) == null || prop.GetValue(LinqObj,
null).ToString() == (new DateTime(1, 1, 1, 0, 0, 0)).ToString())
{
// set the default values here : could re-query the database,
// but would be expensive so just use defaults coded here
switch (prop.PropertyType.ToString())
{
// System.String / NVarchar
case "System.String":
prop.SetValue(LinqObj, String.Empty, null);
break;
case "System.Int32":
case "System.Int64":
case "System.Int16":
prop.SetValue(LinqObj, 0, null);
break;
case "System.DateTime":
prop.SetValue(LinqObj, DateTime.Now, null);
break;
}
}
}
}
catch
{
// could do something here ...
}
}
Related
I have this code to log changes during a save:
foreach (var property in entityEntry.OriginalValues.Properties)
{
if (!object.Equals(entityEntry.OriginalValues.GetValue<object>(property),
entityEntry.CurrentValues.GetValue<object>(property)))
{
this.Events.Add(
new Event()
{
AppUserId = this._appUserProvider.CurrentAppUserId,
EventDate = DateTimeOffset.UtcNow,
EventTypeId = eventTypeId,
RecordId = entityEntry.OriginalValues.GetValue<int>("Id"),
ColumnName = property.Name,
OriginalValue =
entityEntry.OriginalValues.GetValue<object>(property) == null
? null
: entityEntry.OriginalValues.GetValue<object>(property).ToString(),
NewValue =
entityEntry.CurrentValues.GetValue<object>(property) == null
? null
: entityEntry.CurrentValues.GetValue<object>(property).ToString()
});
}
}
I got this from this question
However, I am getting an error on the first line:
Unable to cast object of type 'System.Func`2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.Int32]' to type 'System.Func`2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.Object]'.
It checking the first field which is an int Id field when the error is thrown.
How do I resolve? I don't quite understand what the issue is.
Maybe it worked in Entity Framework, but now doesn't in EntityFrameworkCore?
UPDATE: And suddenly, I realize what the issue is. This is an entity which was added from an API call and the state set to modified, so there is no original value in the StateTracker. So somehow I would need to get the original values to compare to check which values had changed.
The exception is from GetValue<object>(property) call.
The generic type argument of GetValue method is expected to be the exact property type, i.e. cannot be used to get generic value as object.
Instead, you can use one of the PropertyValues object indexers for that purpose, e.g. entityEntry.OriginalValues[property] and entityEntry.CurrentValues[property].
Regarding the update. When you attach entity instance, the OriginalValues and CurrentValues will be one and the same. In such case, instead of the OriginalValues property you could use the result of the GetDatabaseValues method call, e.g.
var originalValues = entityEntry.GetDatabaseValues();
I have Table in Data Set and when i try get cell value if value is null i get exception. Strong Typing Exception
"The value for column Surname in table AI_PARTNERS is Db Null."
Ever time when i try turn
partnersDataSet.AI_PARTNERS[0].SURNAME
if is null i get exception and can't do compare with null.
_partnerInfo.Surname = partnersDataSet.AI_PARTNERS[0].SURNAME
how get the value or empty string if value null?
You can always use one of the DataRow.IsNull method overloads. Also, since you are using typed data set, there must be a generated method called IsSURNAMENull().
But you can get that automatically. Open the typed dataset xsd file in the designer, select the SURNAME property, go to Properties window and change the NullValue property from (Throw exception) (the default) to either (Null) or (Empty).
Reference: Annotating Typed DataSets
try like this
Check your properties with DBNull.Value value
if(partnersDataSet.Tables[0].Rows.Count>0)
{
if(!string.IsNullOrEmpty(partnersDataSet.AI_PARTNERS[0].SURNAME))
{
if (partnersDataSet.AI_PARTNERS[0].SURNAME != System.DBNull.Value))
{
_partnerInfo.Surname =partnersDataSet.AI_PARTNERS[0].SURNAME;
}
}
}
I've made an UltraGrid with Infragistics where I have a column of Datetime type with the format HH:mm.
Normally the column is filled with a value like : "15:13". I can edit it and set what I want then save. But if I delete the field it looks like that : "_ : _" then I save my table, I get back an exception "Specified cast is not valid".
This is because I'm trying to save a value which is not set. I would like to know how to handle this exception.
I tried to compare the fiel to "null" but it does not work.
var newDuration = (DateTime)row.GetCellValue(3);
if (newDuration == null)
{
MessageBox.Show("Please set all the fields.");
}
The dataType of the column is System.DateTime, I set the default value to DB (DBNull) and AllowDBNull is Default.
There are two ways to fix the issue:
display a message to the user to ask him to set a value
If the field is empty, set a default value like 00:00
Ask me if you need more info. Thanks !
Typical pattern to try to get value of wanted type without being sure is
var value = someOtherValue as SomeType;
if (value != null)
{
... // value is a correct SomeType here
}
This works for reference types. In case of structures (DateTime is a structure), which are value types, you'll have to check the type prior
var value = row.GetCellValue(3);
if(value is DateTime)
{
var dateTime = (DateTime)value;
... // dateTime is a valid DateTime here
}
My answer doesn't explain why you have the problem, but shows how to avoid having it (which may not be a good idea, but it seems you want that).
If your value can be DBNull, then simply check for it:
var value = row.GetCellValue(3);
if(value != DBNull.Value)
{
var dateTime = (DateTime)value; // it must work now
...
}
Actually I did this :
try
{
newDuration = (DateTime)row.GetCellValue(3);
}
catch
{
row.SetCellValue(3, new DateTime());
newDuration = (DateTime)row.GetCellValue(3);
}
And it works... Thanks all for your help, I will use what you told in my future dev' !
At the wingrid there is a specific event for handling this errors, its datacellerror quite useful and no need of anything else, hope this its helpfull for someone
In an MVC App we are suppose to dynamically load some strings from database. Basically a <string,string> key-value dictionary. Loading each text each time from the database would kill the application, so those texts would normally be pulled from the DB just once and then stored in cache (namely Web.HttpContext.Current.Cache). There are also default texts that are hardcoded and those would be used if nothing was found in the database. To make things more simple I would also put those default texts in the cache.
The logic is as follows:
Try getting the text from cache and return it if it's found.
If there was no text in the cache, try pulling it from the databaseand and if it's found, save it to cache and return it.
If all above failed, use the default text and save it to the cache so no further queries will be made for this particular key.
If I understand it correctly the only way to check if key is set in Web.HttpContext.Current.Cache is by comparing it's value to a null. My problem is, it's not entirely unlikely that the default text will be a null. So if I put that in the cache, I will not know that the key was set and I will try to pull the non-existant value from the database each time the text is needed.
I know I could use an empty string instead of a null, but it's possible that I might need to distinguish between nulls and empty strings for some reason in the near future.
So is there some way to tell if a key is set in the Web.HttpContext.Current.Cache when the value assigned is a null?
StriplingWarrior beat me to the punch, but I agree with what he said: just wrap what you're storing in a complex type so you can do a null check. Normally you'd use Nullable<T> for this, but you can't use a Nullable type for things that are already considered nullable, like strings.
Here's a practical example:
Define a simple wrapper class:
public class CacheEntry<T>
{
public T Value { get; private set; }
public CacheEntry(T value)
{
Value = value;
}
}
And then use it!
System.Web.HttpContext.Current.Cache.Insert("name", new CacheEntry<string>("Marcin"));
var name = (CacheEntry<string>) System.Web.HttpContext.Current.Cache.Get("name");
if (name != null)
{
Console.WriteLine(name.Value);
}
null is highly overused by most C# developers. If you recognize that these values are optional (meaning they may or may not be there), you may want to make your cache entries be of some type that wraps the actual type you're storing. That way, getting a null value means that there is no entry, whereas getting a non-null value that has a null Value property on it means it exists in the cache, but its value is null.
Incidentally, I've been working on a library to represent exactly this sort of wrapper. It's still in its alpha phases at the moment, but at least for this purpose it should be safe to use. You can get it from Nuget under the name "CallMeMaybe".
object result = HttpContext.Current.Cache.Get(key);
if(result != null)
{
return ((Maybe<string>)result).Else(() => null);
}
var value = Maybe.From(GetValueFromDb());
HttpContext.Current.Cache.Add(key, value, ...);
return value;
Another option would be to use MemoryCache directly, which I think is what backs the HttpContext.Current.Cache these days, but which provides additional methods like GetCacheItem.
If you must store a null in something that doesn't distinguish between nulls and key-not-found conditions, store an "active null" object to represent a null you've actually added:
private static readonly object ActiveNull = new object();
public bool GetIfPresent(string key, out object value)
{
object fromCache = Web.HttpContext.Current.Cache.Get(key);
if(fromCache == null)
{
//failed to obtain.
value = null;
return false;
}
if(ReferenceEquals(fromCache, ActiveNull))
{
//obtained value representing null.
value = null;
return true;
}
value = fromCache;
return true;
}
public void AddToCache(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
{
Web.HttpContext.Current.Cache.Add(key, value ?? ActiveNull, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
}
I have asp.net form with C#, where is I am taking user information to insert in the database as usual by using Linq. well. Where as I am taking Date of birth also from the user, but if user skip to fill date text box from ui, then I am getting date like '01/01/0001' something like this, which certainly database security would not allow to store it.
So I need to check somewhere in my code that it is null or in this (above given) format. If it is null or in format '01/01/0001' then what exactly I have to do? I don't have any default
value for dates.
So what is the standard way to handle if date is null (but not mandatory).Please guide me. So many times I found myself in trap while handling null for various types.
Edited
see what i did seems it working here. but i don't think so this is standard way:
DateTime? otxtDOB = new DateTime();
if (!string.IsNullOrEmpty(DOB))
{
if (Convert.ToDateTime(DOB) != DateTime.MinValue)
{
otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
}
else
{
otxtDOB = null;
}
}
Please confirm me is this right way ?
Making the date property Nullable (i.e. a "DateTime?") should allow it to actually be null if the user hasn't set it. (And provided your database column will allow nulls, it can be stored as null in the database)
Otherwise it's going to default to DateTime.MinValue which is what you're seeing here. And you'll have to explicity test for DateTime.MinValue when adding to the database.
DateTime is a value type (like a number), so you can't assing a null value to it. Mane people use DateTime.MinValue or DateTime.MaxValue instead, but I prefer to use nullable types:
DateTime? nullableDate;
dateSample.Value = null;
you can do some thing like this C# have some features like nullable type you can make use of
this it will save you some piece of code it will be more robust too.
Public int InsertData(int? ouId)
{
chkValue = ouId.HasValue ? ouId.Value : 0;
}
You have the option of using Nullable<DateTime> (alias DateTime?). This makes you able to handle the date as null throughout your application.
However, personally I am not to found of nullables and would prefer this second path: You can use DateTime.MinValue (which is 01/01/0001) as a meaningful constant in your application and the check for DateTime.MinValue in your data access layer.
The database, if it is an SQL Server and the field is of type smalldatetime, would overflow and throw an exception if you tried to save DateTime.MinValue. Null however, may well be stored in the database for any type.
This is how you can parse your strings into nullable types:
private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
if (string.IsNullOrEmpty(s))
return null;
T t;
if(tryParse(s, out t))
return t;
return null;
}
with usage:
var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);
use
DateTime dt;
if(DateTime.TryParse(DatetImeValue.Tostring(),dt)) // datetimevalue is your db value
{
datetimeproperty = dt; // in your class declare it as DateTime? datetimeproperty
}
else
{
datetimeproperty = null;
}
While displaying check for null, if its null set it empty.
[Update]
Do one thing, Keep the property nullable. In your database. Set field to allow null and in the parameter user #DateTimeParam = null.
OR A QUICK WORKAROUND MAKE THE DATABASE FIELD AND PARAMETER VARCHAR INSTEAD OF DATETIME, IN PARAMETER PASS DATETIMEVALUE.TOSHORTDATESTRING() AND ALSO CHECK IF USER SKIPS
PUT STRING.EMPTY IN PARAMETER. IN THIS MANNER IT WILL BE EASY TO YOU TO DISPLAY DATE AND TIME. YOU NEED NOT CAST OR WIPE OFF THE TIME PART IF YOU DO NOT NEED IT
obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));
You can use this while passing to database.
object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
datetimeObj = DBNull.Value;
else
datetimeObj = datetimefromUI;
// Post datetimeObj to parameter in database...