I am new in ASP.NET and C# and use mysql as well as postgresql.
I am trying to store Null value to GUId column in database.but it gives error while saving data because it default take guid.empty value to database.
can anyone please tell how can I store null value from C# code to Database ?
Thanks
Well pretty sure you've basically got two options.
Change the Database column to allow nulls.
Use Guid.Empty and use some logic in your other table population to ensure the column you're referencing elsewhere does not use an empty guid.
This might be bad form(?) but also remember the sheer number of possible Guids, if you're worried about a Guid randomly BEING empty the likelihood of this ever happening unless you're dealing with a staggering amount of records is IMMENSELY unlikely. Provided that is you are using Guid.NewGuid() to generate your Guid of course.
It is likely that you are using the classic Guid structure . If your code looks like this:
public class Dog
{
public Guid Token { get; set;}
}
then you are using the classic Guid structure. Since 'Guid' is a struct type, the reference 'Token' will always have a value, which by default is all zeros. What you want (if you wish to make the Guid truly nullable) is to use the nullable type modifier on the Guid struct. It looks like the following:
public class Dog
{
public Guid? Token { get; set;}
}
Now, if you don't assign a value to 'Token', it will be null.
* Be aware this may introduce subtle changes and hard to track NullExceptions.*
Related
I am getting data with an updated timestamp that I would like to ignore for example:
public record Person
{
public string LastName,
public string FirstName,
public string MiddleName,
[isThereAnAttributeThatICanPutHere]
public DateTime UpdatedAt
}
C# records auto generates code that compares records by value, and I would like to take advantage of that feature but need to exclude one field. I know that I can provide my own GetHashCode but that would defeat the purpose of trying to stay simple. I also know that I can compare with the following:
person1 with {UpdateAt = null} == person2 with {UpdateAt = null} // this will need UpdatedAt to be nullable
but that looks like needless allocations.
No, at the moment there is nothing build in, so unless you are willing to write your own custom implementation (potentially using source generators) you are limited to manual overriding of the Equals (and GetHashCode JIC). Something similar was discussed for PrintMembers in this issue and it seems that attribute approach is not considered by the .NET team.
I created a new column in an existing database, to allow me a RowVersion for concurrency operations:
alter table MyTable add ColumnName rowversion
In my class I added the following property
public byte[] ColumnName { get; set; }
In the one method that uses this class i get the error when using this property
Cannot implicitly convert type 'System.Data.Linq.Binary' to 'byte[]'
I overcome this by adding ToArray (myObj.ColumnName.ToArray()) to the property.
In my ASP .Net page I add a hidden control to a Repeater and assign the value as
RowHiddenField.Value = Convert.ToBase64String(myObj.ColumnName);
Now i am trying to compare this column with the object passed in
public bool RowModified(MyObject myObj)
objFound = GetAllObjects.First(o=> o.ID = myObj.ID);
If (objFound.ColumnName == myObj.ColumnName)
but the values are never the same?
After reading a few links in converting TimeStamp, i've attempted them but either they didnt work (could be i was confused and did something wrong) or it didnt apply to my scenario.
Appreciate any help on this.
I don't know anything about the SQL rowversion format. Seems like the links offered by mss in the comments will help you if you care about that.
But if all you care about is equality, then it should be sufficient to just compare the two byte[] objects. The problem with your code is that arrays don't override Equals() or provide an == overload. So using == just compares the two object references, which are always the same.
See this previously-asked question for details of how to correctly (and easily) compare two arrays:
Easiest way to compare arrays in C#
I read it in "Professional Sitecore Development" book by - John West saying that it's best practice to use Field ID's instead of Field names while getting the Item Field value.
But sitecore Controls like sc:text, sc:link, sc:image etc have an attribute called field which uses field name. So, i am confused now whether to change the whole project to Field ID's or leave it with field names to be consistent with sitecore usage.
Any suggestions will be appreciated.
Yes, Sitecore allows you to use Names and IDs. Also Sitecore allows you to have identical fields names in a same template, what may cause some confusion. IDs, of course, can not be duplicated.
I believe it is more reliable to use IDs instead of names. Names can easily be changed on Sitecore, and it is hard to find the error when that happens. You won't get compilation error or anything like that until someone notice the field value is not there.
A good approach is to use a code generator (like T4 or TDS) to create strongly typed classes to be used in your code. Something like:
public static struct MyTemplate
{
public static struct MyGroup1
{
public static readonly ID Foo = new ID("{1111111-1111-1231-1231-12312323132}");
}
public static struct MyGroup2
{
public static readonly ID Foo = new ID("{9999999-9999-xxxx-1231-12312323132}");
}
}
Then you go that way on your controls:
#Html.Sitecore().Field(MyTemplate.MyGroup.Foo); //where foo returns the id.
Hope that helps..
As an FYI adding to #RobertoBr's excellent answer, Sitecore uses GUIDs internally to access well known fields. If you decompile Sitecore.Kernel.dll and look in the static class Sitecore.FieldIDs you will see a list of fields you would be very familiar with using, e.g.
public static ID Created = new ID("{25BED78C-4957-4165-998A-CA1B52F67497}");
public static ID CreatedBy = new ID("{5DD74568-4D4B-44C1-B513-0AF5F4CDA34F}");
public static ID DisplayName = new ID("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}");
Very similar to what RobertoBr has suggested.
I would recommend you to use field IDs instead of field names in all cases.
Field IDs usage prevents a lot potential mistakes, misspell, etc..
You don't need to worry about correct behavior if you will decide to rename some fields (or other developer will decide to rename his fields).
If you use template's inheritance, you may have potential bugs with duplicates of field names.
Field IDs usage prevents unnecessary processing. Because when you are using field name, Sitecore resolves field ID by field name and after that retrieves field by ID.
I'm working on an ASP.NET MVC app, designing the domain models, using (testing) the new EF Code First feature.
I have an Activity entity that may or may not have a Deadline, what is the best way to approach it?
1 property:
public DateTime? Deadline {get; set;}
and check vs null before using
or
2 properties:
public DateTime Deadline {get; set;}
public bool HasDeadline {get; set;}
At first I thought of the first option, but then I started thinking that maybe the second option would be better regarding the DB...
Is there any best practice regarding this?
I'd go with the first option. After all, it's exactly an encapsulated form of the second.
The encapsulation makes it clear that you've only got one logical value (or lack thereof). In the second form you can treat the properties as if they were entirely independent, which they're logically not.
In terms of the database, I'd expect the first form to be just as easy too... presuambly you'll have a nullable DATETIME field in the database, won't you? It should map directly.
How about a combination of both just for the sake of making your code more readable?
public DateTime? Dealine{get; set;}
public bool HasDeadline
{
get
{
return (Deadline != null);
}
}
Its easy to read and does exactly the same thing that the consumer would have to do anyway. Besides...
if(HasDeadline)
doStuff();
is easier to read than
if(Dealine != null)
doStuff();
:)
I would use the first option. In the long run the second option will probably cause some maintenance problems because you have to remember to check and use both of the properties.
Also one option is to use one property but instead of making it nullable, you could return a Null object (also known as Special Case).
The database is used to storing NULL values - storing a Min value in the databsae, and then having a flag to indicate if you should trust that value makes queries complicated.
I like nullable types since the reflect the domain's intent - there is no date, not 'there isn't a date, so pretend the first of January 1970 means no date'.
There is also an overhead of maintaining the HasDealine value - you need to set it each time the corresponding property is updated. Also how do you clear it? If you set the Deadline to a date, it will set the HasDeadline to true. How do I 'unset' it? Would you set HasDeadline to false, but leave the Deadline field intact with the previous value?
Overall icky.
You should use the nullable, as it does exactly what you want. Using two separate properties means that you lose the connection between them, and you need to explain with documentation that they have a relation.
The nullable type should also fit better against a database type, however you should first design your object for how it works as an object, not for how you will store it in the database. If the use of a database generation tool causes you to make bad decisions when designing the code, it's contra-productive.
Does anyone know of a quick way to have NHibernate insert default values for value types as null into the database?
For example:
public class Foo
{
public int SomeProperty { get; set; }
}
By default, int is 0. When it goes into the database, I would like it to go in as null.
I know I could do this by changing SomeProperty to a nullable int, but perhaps there is another way?
I also know that I could do this with an IUserType but is there an easy way of building a user type that can be generically used for all value types?
This is not a simple way to make NHibe convert 0 to null and vice-versa, but an alternative suggestion (maybe or maybe not right in your situation).
Imo, using a default value to mean null is an antipattern; maybe you agree. I take it that you're trying to hook up some legacy code with a proper database; is that correct?
If you are in control of the business class which you are mapping (class Foo), then I recommend exposing a nullable version of SomeProperty for use moving forward:
public class Foo
{
/// for new code, and for mapping to the database:
public int? SomeProperty_new {get;set;}
/// for legacy code only. Eventually, refactor legacy code to use SomeProperty_new instead, and just remove this needless property.
[Obsolete("This uses default value to mean null. Use SomeProperty_new instead.")]
public int SomeProperty_old
{
get
{
if (SomeProperty_new == null)
return 0;
else
return SomeProperty_new;
}
set { /* convert from 0 to null if necessary and set to SomeProperty_new.*/ }
}
}
You'll want better names than SomeProperty_new and SomeProperty_old, though.
On the other hand, if 0 is never a valid value (except to mean null), you could instead make the DB use a non-nullable value. It really depends on the situation at hand.
You could use NHibernate event architecture and plug a Listener doing the conversion on load, save or update.