one to many relationship in Entity Framework on the same table - linq

I have two tables, in which one user can have several contacts:
User(UserId, UserName)
Contact(UserId, ContactId)
Suppose I would like to get all the ContactNames from the UserNames in the User Table by the Userid.
Note that the Contact table cannot be seen in the current data context, it has been turned into a many to many relationship
How can I do the query?
What If I need to insert or delete?
I tried the "include" method but it does not work. Do you have any suggestions?
Thank you very much.

var id = 1; // id to find
context.Users
.Where(x=>x.UserId = id)
.SelectMany(x=>x.Users)
.Select(x=>x.UserName)
.ToArray();
After generation from db your model has 2 sub-collections: Users and Users1.
One of it corresponds to users, that are contacts for current user.
Another stores users, that current user is contact for.
You can rename them to represent their meaning to Contacts and ContactsFor via editor.
If you still want to have 2 types instead of Type+(Many-To-Many Ref), then in editor you can delete reference, create new entity Contact, setup all mapping, add references. After all this is done - you will have model look like this:
To Achieve this:
Delete Many-To-Many reference
Crete new Entity Contact
Add properties ContactId and UserId, set StoreGeneratedPattern to none
Add mappings for Contact
Add associations for Contacts and ContactFor
But it's not that easy.

Related

Parse - avoid sharing information in specific column of a class

I've got a question about the best way to allow user's information to be visible between users in certain situations.
I have certain columns in User class which are private to the user.
In some activity i'm pointing to user object as 'postedBy' or something else,In this case the entire data regarding user is getting shared.
My question is how to restrict user to get some columns in User class??
usually if you want to restrict an access in parse it should be done via ACL. In ACL you can create role for users who can read/write to the class.
ACL are executed on a class level and not on a column level. In order to expose part of the fields i think you have 2 options:
Create one to one realtionship from your User class to another Class. the second class will contain all columns that not all users can see and for this class create ACL's with the users/roles that can view this data and when you will execute your query only the users with sufficient permissions will be able to get this data
The second option is when you want to avoid relationships here you can use the select option under query. Select allows you to select specific fields of the class and the query will return only the fields that you specified under the select. here is a code snippet from parse docs which explain how to use select (in JS):
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.select("score", "playerName");
query.find().then(function(results) {
// each of results will only have the selected fields available.
});
Hope its clear now :)

How to get entities excluding navigation properties

I am using entity framework 6 for one of my project. It has two entities Employee and EmployeeContacts. One employee can have many contacts and I have mapped these relationship in the database. When I return an Employee object it also returns EmployeeContacts that is related to the Employee. I want get only the Employee object excluding contact details
You can use find: var myEmployee = context.Employee.Find(id);
See https://msdn.microsoft.com/en-us/data/jj573936.aspx

Retrieve data from multiple many to many relationship within the same two tables using LINQ

I have 4 tables:
Accounts
Photos
AccountPhotos (AccuntID, PhotoID) - Holds records of bought photos
for each account
AccountFlagPhotos (AccountID, PhotoID) - Holds records of flagged
photos for each account
Thus I have 2 many to many relationships between the same 2 tables, holding the same data but for different purposes.
I usually SELECT records in LINQ between many to many relationship tables as follows:
public IQueryable<Photo> GetByAccount(string username)
{
//Get the specific Account record
Account myAccount = new UserDAL().GetByID(username);
//Get all photos for that account (many to many)
return myAccount.Photos.AsQueryable();
}
The problem is that this time I have two many to many relationships between the same two tables. How can I determine in the code above from which table (table 3 or 4) I want to retrieve records from?
Go to the Entity Model
Right click on the relationship
Select Properties
Use the End2 Navigation Property
N.B.:
From the diagram you can directly go to the relationship properties by selecting the relationship from the Navigation Properties of a particular table.

How to insert into multiple tables with foreign keys in Joomla?

I want to know how to handle mysql tables created with constraints in joomla.
for a example,
theater_table
id , name, description, image, address, tel, fax ,email
theater_facility_table
id, theater_id, facility_id
facility_table
id, name, description, image
Facility table already filled with data and id is the primary key. When creating a theater I am adding facilities to it. I created facility and theater JTables.
Do I have to create theater_facility JTable too?
Using theater Model class how I insert data to theater_facility table. I know I can insert data after theater stored successfully creating and calling storeTheaterFacility() method where it contains insert query to save required information. But I feel it can't be a good method to do so. Please help me to solve this.
Depending on how you implemented the theater - facility relationship, you can handle insering new data in different parts of your code. I mean, if for example your JTable class (the one that loads theaters) is loading/saving the theater-facilities relationship too, then the same class should delete it.
May be you can take a look at other components (for example, com_content, which relates an article to a category, or K2, where you can have multiple tags related to multiple "items"(articles)), so you can take a look on how do these components handle these kind of relationships.
Another important point you shouldn't forget is to update your facility model / table to delete records from the relationship table upon facility deleting.
I hope it helped!

How to connect a users table correctly to a Membership table, or should you even do that?

I'm probably going about this the wrong way, please feel free to correct me.
Currently I have a User model called U_USER, it contains fields such as address, receiveNotifications, HasCompanyCar Etc.
These users have roles in a .NET Membership table. When the user logs in via Membership, I get their user record in my database as follows (the username on the Membership table and my own U_USER table will have a match):
//Gets the current user
public U_USER CurrentUser()
{
return GetUser(HttpContext.Current.User.Identity.Name);
}
//Gets user details by username
public U_USER GetUser(String username)
{
return (from u in db.U_USER
where u.UserName == username
select u).FirstOrDefault();
}
If I wanted to get a list of all users in, lets say, the "Create" role then I would do this:
allUsers.Where(x => Roles.IsUserInRole(x.UserName, "Create"))
This is a big performance hit as it's doing a lookup for each iteration of a user. This makes me think I'm not going about user management in the correct way. So to answer this question:
How should you properly connect Membership to a users table that in turn is connected to the rest of your data? I'd also accept how to just go about it more efficiently!
Many thanks :)
EDIT :
I've increased performance via the below code. I get the users in the role in one swoop and then filter them.
String[] usersInRole = Roles.GetUsersInRole("CanApprove");
users = users.Where(x => usersInRole.Any(y => y == x.UserName));
But I'm still fairly sure I'm going about this ALL wrong!
Not an expert in this, but what my apps typically do is to use a foreign key (with Index) from my own Users table to the Membership Users table using the Guid field with the Membership. This then allows me to do queries using Linq like:
var query = from myUser in MyUsers
join aspUser in aspnet_Users on myUser.UserId equals aspUser.UserId
join usersInRole in aspnet_UsersInRoles on aspUser.UserId equals usersInRole.UserId
join role in aspnet_Roles on usersInRole.RoleId equals role.RoleId
where role ...
select new { ... };
(Or you can use dot-form like myUser.AspUser.Roles.Role to let the ORM generate the joins if you prefer)
For performance, it's good to watch the SQL trace occasionally - make sure you're not making too many SQL round-trips for each logical step in code.
Hope that helps a bit.
Update - in answer to your questions about "should you even do that", I think "yes" but there are other options available - e.g. you can use Profile fields - see Step 6 in this great walkthrough - https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx
We have created EntityFramework entities for all of the AspNet membership tables, this lets us query them like any other entity.
Not sure if it is what your after but may help

Resources