Entitry Framework Add To Intersection Table - entity-framework

I have a User table and a Group table. Between these is a UserGroups intersection table to allow a user to belong to any number of groups.
The groups table is already populated with values.
How do I add a group to this user so that in the intersection table the relationship between the user and a group is created?
My Primary Keys auto increment.
My DB structure:
My EF structure:
(source: livefilestore.com)

Looks like i was missing the plot aboit.
the solutions is very simple.
Here is a little examle.
Thanks
using (UserEntities ctx = new UserEntities())
{
var group = (from g in ctx.Group
select g).FirstOrDefault();
User user = new User();
user.UserName = "Ian";
user.UserGroups.Add(new UserGroups { Group = group });
ctx.AddToUser(user);
ctx.SaveChanges();
}

Related

EntityFramework, problems to create entity with composit key

I have a database first project and the context/entities are automatically generated with Scaffold-DbContext.
One table (Region_User) in the database is a cross reference table between User and Region, it contains only two fields UserId, and RegionId that together is the composit key for the table.
I'm currently trying to add a new Region_User to a user like below:
var userregions = new List<Region_User>();
userregions.Add(new Region_User { UserId = 1, RegionId = 1 });
user.Region_User = userregions;
and then try to save it to the database I get an error like:
{"Entity type 'Region_User' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method."}
The generated entity Region_User only contains the fields UserId and RegionId..
How should I do to save a new row in the Region_User table?

Linq lambda query to select child and specify parent data

I have two tables, User and Group. I need to select user table and name of the group through lambda expression, and the return type of the method is User table
Below is my schema structure for user
Below is my schema structure for Group table
Try something like;
var query = yourContext.Users.Select(user => new
{
User = user,
GroupName = user.Group.Name
});

Insert/Update data to Many to Many Entity Framework . How do I do it?

My context is =>
Using this model via Entity Framework code 1st,
data table in database becomes =>
1) User Table
2) Role Table
3) UserRole Table - A new linked table created automatically
Model for User is =>
Model for Role is =>
and my O Data query for inserting record for single User/Role table working properly
Now, what query should I write, when I want to Insert record to UserRole table
can someone have any idea
// Fetch the user.
var user = await metadataManagentClient.For<User>().FirstOrDefaultAsync(x => x.Name == "Test");
// If you want to add a new role.
var newRole = new Role()
{
Name = "My new role"
};
user.Roles.Add(newRole); // Adds new role to user.
// If you want to add an existing role
var existingRole = await metadataManagentClient.For<Role>().FirstOrDefaultAsync(x => x.Name == "My Existing Role");
user.Roles.Add(existingRole); // Adds existing role to user.
// Save changes.
metadataManagentClient.SaveChanges();
Or
await metadataManagentClient.SaveChangesAsync();
You might want to set ID as well. But watch out for new Guid() since it generates an empty guid. What you probably want (if you're not using IDENTITY) is Guid.NewGuid().

mvc4 entity query how to improve this so that performance is better

The following code that I will show works correctly but I am wondering if there is a more efficient way of getting this done that can improve performance. The jest of this is that I got 2 tables profiles and followers. This code is supposed to modify 2 records in the profiles table and add a record in the followers table.
[HttpPost]
public void AddFollower(int id,following followers)
{
// me wants to follows followee
int me = Convert.ToInt32(User.Identity.Name);
using (var scope = new TransactionScope())
{
followers.me = me;
followers.ProfileID = id;
// Add new record on followers table
db.followings.Add(followers);
db.SaveChanges();
// Add +1 following for this persons profile & save it
var UserA = (from s in db.profiles where s.ID == me select s).FirstOrDefault();
UserA.following = UserA.following + 1;
db.Entry(UserA).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
// Add +1 followers for this persons profile & save it
var UserB = (from s in db.profiles where s.ID == id select s).FirstOrDefault();
UserB.followers = profiles.followers + 1;
db.Entry(UserB).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
scope.Complete();
}
}
The code above has a twitter like Functionality were if User A decides to follow User B then you most modify both their profiles in the database. This is done by increasing User A following count by 1 and increasing User B followers count by 1 and then offcourse creating that relationship in the followers table. This code works perfectly but I do not know if it could be written more efficient, I am essentially concerned that maybe this code might slow things down if there are a lot of users on the website.
It's really redundant to store the numbers. That is a computed value, which can easily calculated with a simple count.

Many-to-Many Inserts with Entity Framework

Say I have two entities with about 20 properties per entity and a Many-to-Many relationship like so:
User (Id int,Name string, .......)
Issue (Id int,Name string, .......)
IssueAssignment (UserId,RoleId)
I want to create a new Issue and assign it to a number of existing Users. If I have code like so:
foreach(var userId in existingUserIds)
{
int id = userId
var user = _db.Users.First(r => r.Id == id);
issue.AssignedUsers.add(user);
}
_db.Users.AddObject(user);
_db.SaveChanges();
I noticed it seems terrribly inefficient when I run it against my SQL Database. If I look at
the SQL Profiler it's doing the following:
SELECT TOP(1) * FROM User WHERE UserId = userId
SELECT * FROM IssueAssignment ON User.Id = userId
INSERT INTO User ....
INSERT INTO IssueAssignment
My questions are:
(a) why do (1) and (2) have to happen at all?
(b) Both (1) and (2) bring back all fields do I need to do a object projection to limit the
fields, seems like unnecessary work too.
Thanks for the help
I have some possible clues for you:
This is how EF behaves. _db.Users is actaully a query and calling First on the query means executing the query in database.
I guess you are using EFv4 with T4 template and lazy loading is turned on. T4 templates create 'clever' objects which are able to fixup their navigation properties so once you add a User to an Issue it internally triggers fixup and tries to add the Issue to the User as well. This in turns triggers lazy loading of all issues related to the user.
So the trick is using dummy objects instead of real user. You know the id and you only want to create realtion between new issue and existing user. Try this (works with EFv4+ and POCOs):
foreach(var userId in existingUserIds)
{
var user = new User { Id = userId };
var _db.Users.Attach(user); // User with this Id mustn't be already loaded
issue.AssignedUsers.Add(user);
}
context.Issues.AddObject(issue);
context.SaveChanges();