create a sequence of number in .net for primary key sql - asp.net

Can anyone help me with creating a sequence of number in .net for primary key(SQL server). I need to achieve this functionality through .net code. Has anyone ever tried this before?

If you have a set of data with your PK column called RecordID and you want to get the next available one you could do something like this:
var nextId = table.OrderByDescending(x => x.RecordID).First().RecordID++;
However its not perfect as a user could delete the newest record freeing up the RecordID to be re-used. If you have other data that refers to it then it could end up pointing at a different record.
I think #David Tansey's comment was the best advice - use a GUID:
var nextId = Guid.NewGuid();

Related

Invalid Column Name : SQL / ASP.NET

I'm having a hard time debugging a particular problem and have a couple questions. First, here is what's going on:
I have a relatively simple table called Employees, which has a primary key / identity Id. There is also a Username column - which is a GUID foreign key to my aspnet_Users table used for membership. Finally, there is another foreign key Team_Id which points to another table, Teams.
All I'm really trying to do is give a selected employee's Id and pass it to a method in the DAL which then finds the employee with the following statement:
var employee = entities.Employees.Where(emp => emp.Id == employeeId);
Once the employee is retrieved, I want to use another value which is passed to the same method - the selected team's Id - to update the employee's Team_Id value (which team they are assigned to), using the following:
employee.First().Team_Id = teamId;
entities.SaveChanges();
I get the exception
Invalid column name: {Name}
which doesn't make sense to me, because Employee doesn't have a name column.
All of that said, my questions are:
Where could the mix up possibly be coming from? I've tried thinking up a way to step through the code, but it seems like the error is somewhere in the query itself so I'm not really sure how to trace the execution of the query itself.
Is it possible that it may have something to do with my generated Entities? I noticed that when I type employee.First(). Name comes up in Intellisense. I'm really confused by that, since as I've mentioned there is no Name column in the employees table.
Fixed the issue. I just removed the existing Entity Framework Model and re-added it.
As far as the query goes, you can always use SQL Profiler to watch what scripts are actually running. That's a good way to troubleshoot generated SQL anyway.
For your property, somehow that did make it to your class, so your data model thinks it's there, for whatever reason. I'd say just go to your data model (you don't mention if this this is EF or LINQ-to-SQL), and you'll see "Name" there. Just remove it, and it will remove it from the class, and from the data access stuff.

Can I manipulate the guts of a stored procedure with Entity Framework

So far, I've been using classic ADO.NET model for database access. I have to tell you that I'm quite happy with it. But I have also been hearing much about Entity Framework recently so I thought I could give it a try. Actually the main reason which pushed me was the need to find a way to build the WHERE clause of my Stored Procedures. With the classic way I have to do either of the following:
Build the WHERE clause in the client side based on the user inputs and send it as a VARCHAR2 argument to the Stored Procedure, concatenate the WHERE clausewith the main part of the SQL and pass the whole string to EXECUTE_IMMEDIATE function. I personally hate to have to do so.
Inside the Stored Procedure construct lots and lots of SQL statements, which means I have to take all the possible combinations that WHERE clause might be composed of into account. This seems worse than the first case.
I know that EF has made it possible to use Stored Procedures as well. But will it be possible to build the WHERE part dynamically? Can EF rescue me somehow?
yes, you can use Dynamic queries in Linq.
Dynamic Query LIbrary
from scott gu example
var query = Northwind.Products.Where("Lastname LIKE "someValue%");
or some complex query
var query =
db.Customers.
Where("City = #0 and Orders.Count >= #1", "London", 10).
OrderBy("CompanyName").
Select("new(CompanyName as Name, Phone)");
or from this answer Where clause dynamically.
var pr = PredicateBuilder.False<User>();
foreach (var name in names)
{
pr = pr.Or(x => x.Name == name && x.Username == name);
}
return query.AsExpandable().Where(pr);

Database schema advice for storing form fields and field values

I've been tasked with creating an application that allows users the ability to enter data into a web form that will be saved and then eventually used to populate pdf form fields.
I'm having trouble trying to think of a good way to store the field values in a database as the forms will be dynamic (based on pdf fields).
In the app itself I will pass data around in a hash table (fieldname, fieldvalue) but I don't know the best way to convert the hash to db values.
I'm using MS SQL server 2000 and asp.net webforms. Has anyone worked on something similar?
Have you considered using a document database here? This is just the sort of problem they solve alot better than traditional RDBMS solutions. Personally, I'm a big fan of RavenDb. Another pretty decent option is CouchDb. I'd avoid MongoDb as it really isn't a safe place for data in it's current implementation.
Even if you can't use a document database, you can make SQL pretend to be one by setting up your tables to have some metadata in traditional columns with a payload field that is serialized XML or json. This will let you search on metadata while staying out of EAV-land. EAV-land is a horrible place to be.
UPDATE
I'm not sure if a good guide exists, but the concept is pretty simple. The basic idea is to break out the parts you want to query on into "normal" columns in a table -- this lets you query in standard manners. When you find the record(s) you want, you can then grab the CLOB and deserialize it as appropriate. In your case you would have a table that looked something like:
SurveyAnswers
Id INT IDENTITY
FormId INT
SubmittedBy VARCHAR(255)
SubmittedAt DATETIME
FormData TEXT
A few protips:
a) use a text based serialization routine. Gives you a fighting chance to fix data errors and really helps debugging.
b) For SQL 2000, you might want to consider breaking the CLOB (TEXT field holding your payload data) into a separate table. Its been a long time since I used SQL 2000, but my recollection is using TEXT columns did bad things to tables.
The solution for what you're describing is called Entity Attribute Value (EAV) and this model can be a royal pain to deal with. So you should limit as much as possible your usage of this.
For example are there fields that are almost always in the forms (First Name, Last Name, Email etc) then you should put them in a table as fields.
The reason for this is because if you don't somebody sooner or later is going to realize that they have these names and emails and ask you to build this query
SELECT
Fname.value fname,
LName.Value lname,
email.Value email,
....
FROM
form f
INNER JOIN formFields fname
ON f.FormId = ff.FormID
and AttributeName = 'fname'
INNER JOIN formFields lname
ON f.FormId = ff.FormID
and AttributeName = 'lname'
INNER JOIN formFields email
ON f.FormId = ff.FormID
and AttributeName = 'email'
....
when you could have written this
SELECT
common.fname,
common.lname,
common.email,
....
FROM
form f
INNER JOIN common c
on f.FormId = c.FormId
Also get off of SQL 2000 as soon as you can because you're going to really miss the UNPIVOT clause
Its also probably not a bad idea to look at previous SO EAV questions to give you an idea of problems that people have encountered in the past
I'd suggest mirroring the same structure:
Form
-----
form_id
User
created
FormField
-------
formField_id
form_id
name
value

I need help with sql and data relation tables

i building a mini forum site.. and i constructed a few tables.
1) Users
2) Threads
3) Comments
4) Topics
i build a function that would insert a comment each time a user would submit a comment:
string saveComment = "INSERT INTO Comments(";
saveComment += " UsersID, ThreadsID, Date, Comments, CommentResponse";
saveComment += "Values('" + "','";// no idea what to insert in the UsersID
saveComment += "" + "','";// no idea what to insert in the ThreadsID
saveComment += DateTime.Now + "','";
saveComment += CommenttxtBox.Text + "','";
saveComment += commentResponseString + "')";
As you can see the fields have UsersID and ThreadID, both connected by a foreign key to the comments table.
Now, each time the user submits a comment, i guess i need to insert also to the UsersID field (which is an int in the comments table, and that field increases incrementally by 1 in the Users table). How can i insert a comment, and notify the other table not to increase the UserID by 1. in fact i want it the UserID to stay the same for each user submitting a comment..
How do i do that? i need to insert to a few fields in one table (comments) but keep the other tables informed that it is actually the same user who submitted the comment .
Note: i dont know any vb, only c#, and i use visual studio 2010. asp.net
BTW, the way you are inserting is a security issue, you could get SQL injection ...
Use the system.data.sqlclient.sqlparameters to passe values.
You are creating a very standard normalised structure. Your Users table will be responsible for controlling the UserID values that are generated.
You have two situations to cope with when inserting new comments:
The User exists and is logged in.
The User does not exist and is anonymous.
In the first situation, when you are inserting the comments you will not need to bother looking at the Users table. This assumes you have the UserID already loaded (as the user is logged in).
In the second situation, you will first need to a new row to the Users table and return the UserID that the table generates (assuming you are using an identity column). You can then pass this value to the Comments table.
The following script is an example of addressing the second situation:
DECLARE #userId int
INSERT INTO Users (Username, FirstName)
VALUES ('adamh', 'Adam')
SET #userId = SCOPE_IDENTITY()
INSERT INTO Comments(UserId, ThreadId, Comment)
VALUES (#userId, 1, 'My comment')
If you want to continue with your current coding style, simply concatenate the values into the relevant parts of the string.
However, with such as neatly defined structure as the one you have, I'd advise using something like Entity Framework 4.0, or LINQ to SQL, which cuts a lot of plumbing out once you have defined your structures.

ASP.NET Get a single value returned from TableAdapter Select Query

I'm using TableAdapters on my ASP.NET Project and I've become stuck on an issue of the way to retrieve this data.
The code is as follows:
BookingDataTableAdapters.bookingTableAdapter ta = new BookingDataTableAdapters.bookingTableAdapter();
String booking_id_string = Request["id"];
int booking_id = Int32.Parse(booking_id_string);
BookingData.bookingDataTable table = ta.GetOwnerUsername(booking_id);
String username = string.Empty;
foreach (DataRow dr in table.Rows)
username = dr[0].ToString();
However this will error with the following:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
However when I run the query in the query builder, it runs fine without error. I've have also disabled "EnforceConstraints" inside the table adapter xsd file properties.
I've no idea what's wrong, is there a better way for me to get this single value back from my query in ASP.NET
Many thanks in advance, I appreciate the help :-)
What that tells me is that BookingData has been changed in the database and the object in your project was not updated. When you get the row it cant fill the object because perhaps the database has a null and the object does not allow it. Update the dataset.

Resources