I have 2 tables
User
Access
In the user table I have 4 columns in total but 1 in foreign key of another table (Access).
UserId
UserName
UserEmail
AccessId(FK)
And in the Access table I have 2 columns
AccessId
Yes/NO
I'm able to retrieve the UserId but not AccessId because it is a foreign key in User table.
Here is the code I have written
var test = (from userName in User
select userName.AccessId).ToList();
This is the result I get
System.Collections.Generic.List`1
I want to get the AccessId as well, can you help me please?
Well
var test = (from userName in User
select userName.AccessId).ToList();
Returns a list, so that is what you get. A list of AccessID's.
If you need the ID;s
foreach (var aSingleAccessID in test)
{
// do something with each accessID
}
Related
So my question basically has to do with nested models or associated tables (not sure the correct term).
Specifically when TableA has an ICollection of TableB objects and TableB has an ICollection of TableA, how do I then save off my entire TableA model along with it's assocaited Table2 items.
For example:
User table with: string name, string address, ICollection < Orders >
Orders table with: OrderID, Total, ShipDate, ICollection < User >
So I have a User instance (UserA) which has the name and address set along with a collection of orders (Let's say Bob Dole, 1234 Main st, [567, $12.34, Oct 1; 999, $27.89, Nov 5;]).
How do I trigger the save method to save both Orders & the User?
My expectation would be "db.User.add(UserA); + db.SaveChanges();". I would expect this to save the User and upon seeing the Orders collection, save those as well.
However, previous developers did this:
User userB = db.User.Add(new User(userA.Name, userB.address)); //Why do we have to create a 2nd instance of a User object, that will hold the same information as userA?
foreach(Order order in userA.orders)
{
Order NewOrder = db.Orders.Add(order); //This now updates the Orders table with new info, which will be saved by 'db.SaveChanges()'
NewOrder.User.Add(userB); //How does this update the value in the Orders table with the userID? Isn't this updating the object about to go out of scope?
}
db.SaveChanges()
The only thing we can think, is the way they did it userB get's 'ID' assigned from the .Add command. But couldn't you simply say "userA = db.Users.Add(userA)" in order to update the instance with the ID provided upon database insert?
First of all, I think, you've got to change your schema.
There will be one-to-many relationship between User and Orders. One user can have multiple orders but one order can not belong to multiple users. i.e. Only Order table would have UserId.
Update
Further, No need to add Orders data separately. As there would available collection type in the User table's entity.
You need to just assign values to the User table's entity along with Orders field and do insert it only once.
The code would be somehow as below:
var userData = user;
var orderData = orderCollection;
userData will be single record and orderData could be multiple.
Now assign that data to User data model:
var userAndOrder = new User
{
Name = user.Name,
Address = user.Address,
Orders = orderCollection.Select(o => new Order
{
//assign order fields here
}).ToList();
};
Then save this data. It will save Orders data itself in the Order table against the UserId.
db.Add(userAndOrder);
db.SaveChanges();
Let's suppose that I have a database containing Artists and their Albums.
CREATE TABLE Artist (
ArtistID INTEGER PRIMARY KEY,
ArtistName TEXT NOT NULL
);
CREATE TABLE Album(
AlbumName TEXT PRIMARY KEY,
ArtistID INTEGER REFERENCES Artist(ArtistID),
Year INTEGER
);
So then I create an application inside of Visual Studio and connect the SQLite database to my project using sqlite/sql server compact toolbox, I then want to manage the database using C#
I create an application for my users. A user wants to find all the albums by a name of an artist.
If my primary key is an autoincrement property, do I have to use syntax like :
public static IQueryable<Artist> GetPossibleArtists(string name)
{
var matches = from match in dB.Artists where match.ArtistName == name select match;
return matches;
}
public static Artist GetFirstArtistIfExists(string artistName)
{
var artistMatches = GetPossibleArtists(artistName);
if (artistMatches.Count() == 0)
return null;
return artistMatches.First();
}
So that I first access the database to find the artist by its ID because I can't simply find albums by the artist's name, because the artist's name is not a primary key and I can't search the "Albums" table by the artist's name, I can only search this table by the artist's ID
And then I can finally find all the albums by the artist's id
public static IQueryable<Album> GetPossibleAlbums(long artistID)
{
var matches = from match in dB.Albums where
match.ArtistID == artistID
select match;
return matches;
}
The questions are :
1) What am I doing wrong here and is there a better way to access all the albums of an artist so that I do not need to access the database to "find the ID of an artist by its name" first before I manage to find all the albums by the artistID?
2) I could possibly design my database wrong, are there any suggestions?
3) Is it a good idea to store the artist's name inside of the "Album" table and how do I need to do this to keep my Artist's autoincrement primary key exist at the same time?
You need a JOIN to associate the Albums table to the Artists table on the ArtistID field
var matches = from a in dB.Albums join b in db.Artists on a.ArtistID equals b.ArtistID
where b.ArtistName == artistName
select a;
join clause C# reference
I have a question about foreign keys in a database. I am programming in c#, using the Entity framework (visual studio winforms) and I have data in my sql database with foreign keys.
I have queries which access these data to get them in a Datagrid. Everything is OK, except I have data in tables which are foreign keys (numbers). When I select them with queries I only get the foreign key (a number) and not the value which is linked in another table.
var requete_reservations = from reservation_spa in bdd.reservation_spa
where reservation_spa.NOMBRE_RESERVATION > 0
select new
{
reservation_spa.CLIENT,
reservation_spa.SPA,
reservation_spa.NOMBRE_RESERVATION
};
dataGrid_reservations.DataSource = requete_reservations.ToList();
In reservation_spa.client I have a number which links another table client
How can I get the Name from client using the foreign keys in reservation_spa?
You must Join table reservation_spa and Client like this :
var requete_reservations = from r in bdd.reservation_spa
join c in bdd.client on r.CLIENT equals c.IDCLIENT
where r.NOMBRE_RESERVATION > 0
select new
{
c.NOM,
r.SPA,
r.NOMBRE_RESERVATION
};
Where is the name for? If you just need the name you could use linq
var name= from c in bdd.Clients //Is that the name of the table of clients?
where c.IDClient= requete_reservations.Client
select c;
My problem is that i have 2 tables one about movie datas and the other about rentals and the primary key is the movietitle from the first table and the movietitle foreign key is in the rentals table.
I would like to delete the full row from rentals when on my form user select a movie from the listbox (data from movie table) and the full row from the rentals table becomes deleted (i am trying to delete the primary key of rentals but i get error on the second line :
Error 13 The best overloaded method match for 'System.Data.Objects.ObjectSet.DeleteObject(movies.Rentals)' has some invalid arguments)
var search = (from g in db.Rentals
where g.Movietitle == (string)listbox1.SelectedValue
select g.Szigszam // this is the primary key in the rentals table,the foreign key is the movie title)
.First();
db.Rentals.DeleteObject(search);
db.SaveChanges();
You must do like this.
var search = (from g in db.Rentals
where g.Movietitle == (string)listbox1.SelectedValue
select g).First();
db.Rentals.DeleteObject(search);
db.SaveChanges();
can You help me in this situation
I have three tables
first stored usersgroup
ugroup - primary key
groupname - group name
second stored users
uid - primary key
ugroup - int
username
and so on
.....
third table has list of teachers for each user
teachId - primary key
uid - int
..........
so this query work fine in controller
var viewUsers= db.UsersGroup.Include("Users").ToList();
and in view
I can outp all my groups and users which are in them
#foreach(var ug in #Model.viewUsers)
{
ug.groupName
foreach(var u in ug.Users)
{
u.UserName;
}
}
so but I want to build table in view to show this info:
<caption>GroupName</caption>
<th>UserName</th><th>Count of teachers</th>
<td> John Smith</td><td>3</td>
So how should i build a query to build table in my View like above?
And I if you can give some link where can i read about how can i use EF to make varios queries to my database (like joins uinions and otheres) and I don't understand how work Include() method
i try to chnge my prev string like : db.UserGroups.Include(ug => ug.Users) but it does not work :(
Thank You.
var viewUsers= db.UsersGroup.Include("Users.Teachers").ToList();
and then in the view you can get the Teacher list for each user
#foreach(var ug in #Model.viewUsers)
{
ug.groupName
foreach(var u in ug.Users)
{
u.UserName;
<th>u.Teachers.Count</th>
foreach(var teacher in u.Teachers)
{
<td>teacher.Name</td>
}
}
}