Multiple users but storing data in same tables - c#

Hi I am new to databases in general, so forgive my noob question below, but I really do need help.
I have designed a database with 4 tables. I have created an application in C# which will store some values in these 4 tables during the course of the application running. However, this is all working fine when there is only one user of the application, but if more that one user is going to use the same application running in an ASP.NET page, then they will be accessing and altering the data in the 4 tables, and problems will soon arise.
My question is, how do I prevent this from happening? I want each user to have their own unique username and then use that to differentiate them in the tables but my knowledge of databases is limited to know how to achieve this. Please help?

Supposing you have the following table today:
FavoriteFood
—————————————
FoodId
FoodName
And it lists all of your favorite foods. But then you decide you'll let me use your database to store my favorite foods too. Since you don't care about my favorite foods, and I don't care about yours, you need a way of keeping them separate. First, you'll create a User table:
User
—————————
UserId
UserName
FirstName
LastName
Then, you need to relate the User table to the FavoriteFood table. One way of doing this would be to add a Foreign Key to the FavoriteFood table. Give it a new field called UserId:
FavoriteFood
—————————————
FoodId
UserId
FoodName
Then you can get just the food for a single user by adding a WHERE clause to your SQL code:
SELECT FoodName
FROM FavoriteFood
WHERE UserId = #UserId
That could be ok, but I'm not satisfied with it. This database is not normalized! Suppose, you later want to store calorie information about your foods. You add a field called calories to your FavoriteFoods table. As you are populating that field with data, you notice that you are putting in the same data multiple times. All of your users like bananas, so you have as many entries in your table for bananas as you have users. You have to enter the exact same calorie information over and over again. Instead, you should have all the information for a food in the table just once, and use a completely separate table to map food to users:
Food
—————————
FoodId
FoodName
Calories
FavoriteFood
—————————————
FoodId
UserId
Use a join to get the favorite food for a user:
SELECT f.FoodName
,f.Caloires
FROM Food f
JOIN FavoriteFood a ON a.FoodId = f.FoodId
WHERE a.UserId = #UserId

Related

Is there a way to search a list in a SQLite database?

I am creating a health and nutrition application and I am using unity as my engine. I have a SQLite database which holds the recipes, the fields are ID (primary key), Name, Ingredients and Method. Each recipe is a record in the database and they have their own lists of ingredients. The intent is to allow the user to input ingredients and the program will filter the recipe by ingredients
I expect that when the user inputs flour (as an example) it will show all the recipes that use flour. E.g.: Apple pie, cake and so on. Instead if i want to search the ingredients the input has to be identical to the entire lest
You need to read up on how relational databases work. Right now, with everything in one table, your database isn't really any more useful than a simple Excel spreadsheet.
You want three tables; one for ingredients, one for recipes, and one to join them, which I'll call Ingredient_Recipe. Ingredient_Recipe table will have two foreign keys, one from the ingredients table, one from the recipe table. Then you can do SQL queries like this example:
select Recipes.recipeName
from Recipes
INNER JOIN Ingredient_Recipe ON recipe_ID = Ingredient_Recipe.recipe_ID
Where Ingredient_ID = "oregano"
Which should tell you every recipe that contains oregano.
the classic relational way to do that is to have an ingredients table and a relator table (ingedientrecipe) so that you can query for all the ingredients in a recipe or all recipes that contain a given ingredient

How to check if the item has dependencies in the database before updating its status?

I am a new developer of ASP.NET and Linq-To-Entities. I am trying right now to write a general method which will take care of checking if there is any dependency on the item before updating its status. For example, there are many employees under each division. What I want to do that when the user wants to update the status of the division from an Active to Inactive, then this method will tell him that there are active users underneath it. of all users belong to that division will be inactive. This thing is applicable to the other scenarios such us Department, Division and Unit.
I have the following Database structure:
Departments Table: ID, Name, Code, Status, UserId
Divisions Table: ID, Name, Code, Status, UserId, DeptID
Units Table: ID, Name, Code, Status, UserId, DivID
Users Table: ID, Name, Status
Status Table: ID, Status
Could you please tell me how to do that?
Looks like you need to rethink your model if you're expecting multiple users per Dept/Div/Unit, because your current model only has one user for each, which I assume is not what you want. Also it doesn't seem like you want the opposite either (A user belonging to a single Div/Unit/Dept, which would be done by adding DeptId etc to the Users table.)
Instead it looks like you want a many-to-many relationship between Departments and Users, and the correct way to model this is to give those relationships a dedicated table, such as the following:
CREATE TABLE DepartmentUserRel
(
DepartmentId int,
UserId int,
PRIMARY KEY(DepartmentId, UserId)
CONSTRAINT FK_DepartmentUserRel_Department FOREIGN KEY (DepartmentId)
REFERENCES Department (Id)
CONSTRAINT FK_DeparmentUserRel_User FOREIGN KEY (UserId)
REFERENCES Users (Id)
)
Similar tables should exist for each many-to-many relationship between two of your other tables, but they're not necessary for many-to-one/one-to-many relationships.
Once you have the right model, you should really reconsider storing computed values such as Status in the Departments table at all - you should in fact compute them each time you query, and updating the Status should mean updating all users, not just the Status field in the Department.
You should instead use views to create a virtual view of the database structure as you placed it in your question. If we assume the above DepartmentUserRel table has another Status bit, field in it, where TRUE would indicate an active user and FALSE inactive, such that you want to declare a virtual Status field in the Department table which is true if any of the users for that department are active, you create the view something like this:
CREATE VIEW DepartmentView AS
SELECT D.Id as Id, D.Name as Name, Code, SUM(DU.Status) as Status
FROM Departments D, DepartmentUserRel DU
WHERE DU.DepartmentId = D.Id
You query from the DepartmentView much the same way you would query from a regular table, eg SELECT * FROM DepartmentView
Here's the caveat: Views can not be directly inserted or updated, because they may take fields from several tables, but INSERT/UPDATE should only modify one table at a time. We do in fact only want to update one table at a time here - the DepartmentUserRel table. If we want to set Status in DepartmentView to FALSE (inactive), that instead means we want to set Status in the DepartmentUserRel table to FALSE for all relationships of users to that department. We can do this by creating a trigger which catches attempted updates to the view.
CREATE TRIGGER IO_Trigger_Update_Department on DepartmentView
INSTEAD OF UPDATE AS BEGIN
IF ((SELECT Status FROM inserted) = FALSE)
UPDATE DepartmentUserRel SET DU.Status = FALSE
FROM DepartmentUserRel DU, Departments D
WHERE DU.DepartmentId = D.Id
END
(Note that all those code examples are conceptual. I've not tested them and only partially remember the syntax for them, but you should be able to fix them by knowing what to search for.)

Making a page where each user has his own information,gridview etc

After the user logged in , I need a page where each registered user has his own gridview and controls binded to his gridview.
The page will contain a sqldatasource binded to the gridview .
I thought about making a new table in the database for each user and in the form load to get the username after the user logged in, get the table name and replace the sqldatasource bind to his table name and the other controls fields for table name to his one.
Or is there any other way of doing this?
You definitely do not want to make a separate table for every user. How on Earth would you plan to scale that to multiple users?
What data does the user need to see on their page? Understand that a gridview doesn't have to map directly to a database table. It can map to any set of data. So you can store the data in your database in a way that makes sense to persist it (relational entities), then query and display it in a way that makes sense to display it.
For example (and it's a contrived example, since we don't know what data you have), if you have users who need to see a list of products that they've ordered, then you wouldn't create a table of products for each user. You'd probably have a table for each of the entities (User, Product, Order, etc.):
Users
----------
ID
Name
etc.
Products
----------
ID
Name
etc.
Orders
----------
ID
UserID
DateOrdered
etc.
And since each order would have a list of products, and each product can be on many orders, that's a many-to-many relationship. So you might create a linking table for that relationship:
OrderedProducts
----------
OrderID
ProductID
Then, for displaying in the UI, you would query the data to get only the products ordered by that user:
SELECT DISTINCT
Products.ID,
Products.Name,
Orders.OrderedDate
FROM
Users
INNER JOIN Orders ON Users.ID = Orders.UserID
INNER JOIN OrderedProducts ON Orders.ID = OrderedProducts.OrderID
INNER JOIN Products ON OrderedProducts.ProductID = Products.ID
WHERE
Users.ID = #userID
This should give you a list of distinct products ordered by that user and when they were ordered. (Note that this code is free-hand, I don't have a database handy to test it.)
So each user would see their own specific information.
You want to make sure that your data is modeled in a usable relational fashion. Define your entities (usually real-world things you're representing in the data) and define tables to represent those entities. Relate them together in natural ways. Relational databases are great at handling complex queries against well-defined data. Don't try to design your database around the nature of the display from the perspective of the user, design it around the nature of the information being stored.
You certainly DO NOT need a separate table for each of your users!
Why don't you just add an additional column to one of your tables to store the username. This way, each record is marked to belong to specific user. Reading the data for logged user is just a matter of simple Where clause on the table.
No thats not right,
You can't create a table for every user. Think if you have 10,000 users than you mean your database contain 10,000 users.
You have to create only one table in which all user's information is saved.
You have to save an identity like user name or email to your database and
When user login to your app by his username or email the information will be taken from table on the basis of username or email and set to gridview.
May it helps you...
this is not Logical to create a table for each user,save all user information in a table is better and faster
for this your can make a table for user information with a user id, and another table for user data entery.and make a relation ship between them

How to create table of tables c# my sql

I got site for selling products. In my database I have 3 tables: Users, Countries, Products.
Each user can sale his products in many countries.
When clients come to visit, my site, they can choose to search for product by country and by product price( same product sold by same user can have different prices in each country).
I thought about two implementations for this:
Create a linked table with user_id, country_id, product_id. In this case each time I would like to add new product I will need to update two tables, the linked table and the products table.
Or create new table for each country, that will have products in it. So when I will have to add new product I will only need to update one table.
I like my second solution more, because I think it will perform faster, for both reading and inserting, how ever it's management is hard, I will have lots of tables, and what if instead of counties I would like to use cities, I will get thousandths of tables.
Is there a way in MySQL to create a table of tables?
What do you think about my design will it rarely perform faster?
Do NOT go for the second solution. Relational databases are meant to have a fixed number of tables, and you will run into a lot of problems if you try to have a variable amount of tables in the manner you describe.
If I understood your requirements correctly, you should probably use two linked tables: one that contains user_id and country_id (thus telling where each user may sell products), and one that contains country_id, product_id, and price (thus telling the price of each product in each country). (This assumes that a product costs the same within a country no matter who sells it.)

Dont want to keep same record in two fields/tables in database

I have following scenario
I have news web application
I have two tables
1-User (Register user with news website)
2-Comment table and in comments table there are following some fields
Comments(Comments against any news)
userID (which user comment on agaist this news) // it is foreign key
NewsID
UserName(same as userID which user comment on agaist this news) varchar // this field using for non register users
Scenario 1:
If registered users comments then I insert comments with newsid and userid
in comments table,UserName is null in this case
Scenario 2:
If non registered user(or you can say guest) comments on news then I use UserName filed not userID UserID is null in thse case
I dont want to keep record of user with two places one is in user table and second is for
non register user scenaro in UserName field of Comments table
What you suggest
You could manufacture unregistered users and put them in the Users table and link them with a cookie so they keep using the same information. I think this may be similar to the way StackOverflow handles the anonymous users.
I don't see that big of a problem with your design though. Put a constraint on the table so that exactly one of the two is NULL, and use a COALESCE in your retrieval to get a single user name in the result set:
SELECT COALESCE(User.UserName, Comment.UserName) AS UserName --, etc.
FROM Comment
LEFT JOIN User
ON User.UserID = Comment.UserID
You can hold another table along with your other tables
guests which contain a username and userid field
users which contain userid field and other fields as you would like.
You can then cross-reference your comments userid column with the 2 userid columns above, to fetch the username and other information, this way you'll eliminate the need for a username column in comments
Stay with those 2 fields in comments table. Create Anonymous user in Users table and always populate both files.
For anonymous user:
userId = Id of that single anonymous user in User table
UserName = anonymous user name
For registered user, in UserName field would be duplicated value from Users table
That would have performance benefit when displaying a news comments, as you always (I guess) need to display UserName next to the comment, but don't need user's more details immediately, so no need to join users tale in the query for the news comments.

Categories