How to generate a uniqueidentifier in sql if null - c#

I am trying to add a column to an existing SQL table of uniqueidentifier type. That column must not be null and of course unique. I have attempted this code:
ALTER TABLE ScheduleJobs ADD CurrentInstanceID uniqueidentifier not null
followed by:
ALTER TABLE ScheduleJobs ADD CONSTRAINT DF_CurrentInstanceID DEFAULT newsequentialid() FOR CurrentInstanceID
However, when I create a new record (from C#), the uniqueidentifier is always all zeros (presumably null.) I can create the GUID in C# and pass it to sql upon creating a new record which works fine, but I am concerned that a duplicate GUID could be created. Based on my readings, it appears that would be an extremely rare case, but it always seems bad practice to have any sort of potential error floating around. Note that the field will not be a PK for the table. Suggestions and opinions welcome for the sake of education.
I am using C# 4.0 framework with MS SQL SERVER 2008

Sorry for the delay, but I am glad to say that I have this issue resolved. Thanks everyone for your overwhelming support. While no one quite hit the nail on the head (and there were some really good suggestions btw), Eldog brought up Entity Framework not playing nice in his comment. Thanks to him, I simply Googled Entity Framework + GUID and found the solution.
This article steps through the issue and gives a great explanation on the problem, solution, and steps to resolve it. I will note that I decided to step through and test one step at a time and that I didn't have to do the last step. That leads me to believe that part of the issue may have been resolved in later versions of the Entity Framework.
I simply pulled up the edmx file in design view (not xml) and set the StoreGeneratedPattern property to "Identity."
Thanks again for the help and suggestions. You're an awesome bunch.

Does your C# code attempt to pass in a CurrentInstanceID when creating the record? If so, can you drop that column from the INSERT statement?
We do this with numeric primary keys. Our C# code calls a stored procedure for CRUD operations on our records. The C# code generates a negative key on the client side for its own use. When it is ready to create the record, it passes this key to the stored procedure.
The proc ignores this key and inserts the rest of the data. The output of the proc is the actual key that SQL assigned to the record. Finally, the C# code merges the new key into the existing data.

I wouldn't use a GUID for this. GUIDs are used in quite a lot of operations in windows, so this won't be an identifier that will be only unique in your application, it will be a unique identifier in your operating system. Unless this makes sens in your case, I wouldn't use it.
You could use an incremental value, like a simple uint. If your table already has some data, you could write a script that fills existing rows with incremental values for your new column, and add the unique contraint to your column after executing that script.

in your original Create table or alter table use something like the following
create table ScheduleJobs (keyval int, id2 uniqueidentifier not null default newsequentialid())
then don't reference the column in your insert and a new GUID value will be added

Related

Best practice for data version control in sql and c#

In this question i want to figureout, what is the best practice to control versions of data in sql. We are useing a relational database (Sybase SAP Sql Anywhere). The problem is, we don't know in which layer of our software we should implement a version control system. We want to write a generic system, so that version control is available for all types of data with a small amout of work for every type (Types: Contacts, Appointments, ...).
Here are the options we figured out:
1. Using an entity framework and calculating the difference of two models. Then saving the difference to the database
2. Using triggers and comapre old and new data and save them in separate table
3. Using procedures which proof for changes and save them also in a separate table
I know it's a very general question, but maybe some one has a good idea and solution for our problem.
Edit
Important: I want to create versions of the data itself, not of the sql schema or some sql code.
EDIT2
Lets use the following simple example. I have a tiny contact table (not our real contact table):
CREATE TABLE Contact
(
"GUID" Uniqueidentifier NOT NULL UNIQUE,
"ContactId" BIGINT NOT NULL Identity(1,1),
"Version" INTEGER NOT NULL,
"FirstName" VARCHAR(100),
"LastName" VARCHAR(200),
"Address" VARCHAR(400),
PRIMARY KEY (ContactId, Version)
);
No, every time some one made changes to the contact object, i want to save a new version of it. But im am looking for a general solution. This must be implemented for every type.
Thank you!
As someone who live and breathe database source control (part of amazing team at DBmaestro), I can recommend on combination of 2 methods, depending on how you run the delta.
Using triggers you should save all information you need for the deployment, if it by using slow change dimension or entire table content
Using procedure that analyze difference and knows to generate the relevant delta script
we have the same issue and try to solve it by storing a version and a branch id with every entity we want to follow.
In a different table we store the versions with their predecessor version id, so we can trace where branches meet each other.
Seperatly we have an audit trace with the version number.
I wonder if this has the same elements you need(ed) and whether you advanced since your question and your last edit.
Thanks for the suggestion to combine the unique id and the version number

ADO.NET data model generate from database is leaving out one of my tables

I am trying to add a ADO.NET to my asp.net project.
It generates everything correctly, except it leaves out one of my tables,
I have a feeling it might be due to a naming issue or something,
It add my one tables called Users but then the table it is excluding is called 'UserCompanyhow ever I have tried turning off the option topluralize or singulise generated object names` and it still does the same,
The UserCompany Table is a simple table consisting of two ints,
Userid , CompanyId
Is there a an issue or a common bug that I am not aware of? ANd how cna I work aroudn this, as I have been using the model successfully up until now where I need to use the one table which aint there.
I found out the issue,
My one table did not have a primary key, And as far as I know EF requires that your table have a primary key.

C# integer primary key generation using Entity Framework with local database file (Sdf)

I'm writing a standalone application and I thought using Entity Framework to store my data.
At the moment the application is small so I can use a local database file to get started.
The thing is that the local database file doesn't have the ability to auto generate integer primary keys as SQL Server does.
It's not a problem defining the ID column as "identify" when creating the table, but when trying to call the SaveChanges method it throws the following exception:
{"Server-generated keys and server-generated values are not supported by SQL Server Compact."}
Any suggestions how to manage primary keys for entities in a local database file that will be compatible with SQL Server in the future?
Thanks,
Ronny
There are three general techniques I can think of for where the database has no auto-number.
1) Do a MAX(ID_column)+1 first to get the next ID value. However, you need to be aware of multi-user issues here. Also, the numbers are not one-use-only. If you delete a row and add a new row, you will get the same ID. This may or may not be a problem for you.
2) Use a GUID. Pretty much guaranteed to be unique, but does have a large footprint for an ID column.
3) Use a separate key table that holds the last ID that was assigned. This ensures numbers are never reused, but adds an extra table into your database.

how to insert data in sql table using Linq without seting any primary key in table

I have a Table in which i don't want to specify any primary key, after that i am inserting records in it using Linq...aahhh...its giving the error
"Can't perform Create, Update or Delete operations on 'Table(abc)' because it has no primary key"
can ani one tell me how to insert record without setting it primary key.
By the way im not setting any primary key because this table will have bulk of data to keep.
You can't use Linq-to-SQL directly with tables that don't have primary keys, because it's not supported.
If you're worried about the performance hit of indexing, what you can do is add a Stored Procedure that does the insert and add that to your data context. It's a bit more work, and it's not really Linq-to-SQL, it'll just be a method on that you call on your data context.
There probably won't be a noticeable performance hit on an identity primary key field anyway.
Tami - would it not be a good idea to stick to 'best practices' when using linq and add a autonumber primary key, even if it isn't going to be used other than for inserts or updates?? i can think of many instances where the seemingly 'non requirement' for a primary key later leads to trouble when trying to update to other platforms etc.
If there's a compelling reason to not add a 'blind' primary key, then it might help to detail this as well in the question. I can't think of any reasons not to add it, especially if it means that you don't have to code around the limitation.
jim
[edit]
Tami - i'll be honest with you. you might have to investigate conventions to best satisfy any answer to this question. basically, altho' you don't 'need' an index on your records, due to not being edited or deleted, the convention with linq is based around the assumption of data integrity. in essence, linq (and many other programatic tools) require a convention that allows them to succinctly identify a unique key on each object that they bring into scope. by not defining this, you are by-passing this convention and therefore linq is flagging this up for you. the only way fwd is to go with the flow. even if you 'feel' that the index is redundant, linq requires it to allow you to access the full functionality built into it.

Letting the database pick the primary key in nhibernate

How do I just simply allow MySQL to assign a primary key to an inserted object with nhibernate? It seems I would want to set the generator as a type "identity", but the documentation states that using this "..require[s] two SQL queries to insert a new object." Why would it do that? Is there some way to get this functioning like a normal insert sql statement?
The reason that it requires two queries is that with an identity the value of the column is not defined until the row is inserted. Therefore it requires a select after insert to get the column value for the inserted object. This is pretty standard and I wouldn't let it stop me from using autogenerated keys as my primary key. The other option is to pre-generate the key -- say a GUID for the new object before persisting it to the database. For the most part I don't really see an advantage to this unless there are other mitigating circumstances, such as having to merge data from separate databases where autogenerated keys might collide.
There's an obvious advantage: Letting NHibernate use Guids or Hilo as the id generator will enable an extremely cool feature in NHibernate: batching. Just configure NHibernate to use batching (for like, say 1000 statements), and your inserts will suddenly be extremely fast.
Fabio has a post about the various availabe generators here - extremely useful reading if you are using NHibernate (or if you know someone who thinks NHibernate performs badly).

Categories

Resources