Reputation: 71
I am using Entity Framework 6
public class ALLEvent
{
[Key]
public long Eventid { get; set; }
public string eventname{ get; set; }
public string AttendingUsers{ get; set; }
public virtual List<User> Users{ get; set; }
}
public class Users
{
[Key]
public long id { get; set; }
public string Name{ get; set; }
}
I have an AllEvent
Class, in AttendingEvent
property I have a list of attending UserId
s separated by a comma. Is there any way I can get a list of attending users in the Users
property of AllEvents
?
Upvotes: 1
Views: 418
Reputation: 14488
You will have to do a query for every event to get the users:
using(var ctx = new MyContext())
{
ctx.Configuration.LazyLoadingEnabled = false;
var events = ctx.AllEvent.ToList();
foreach(var event in events)
{
event.Users = ctx.Users.Where(u =>
event.AttendingUsers.Split(',').Cast<long>().ToList().Contains(u.id)).ToList();
}
}
A much better option would be to make the Users
have a foreignkey to an event (except if it's many to many, then you'll need an intermediate table). Then you can use lazy/eager loading. At the moment the virtual
keyword doesn't do anything in your Event
model because there's no relation between the entities.
Edited answer because cast from string -> long is needed.
Upvotes: 0
Reputation: 541
You could do it with Select:
allEvent.Users = allEvent.AttendingUsers.Split(',').Select(
u => new User
{
Id = Convert.ToInt64(u)
}).ToList();
Or with a foreach loop:
var users = new List<Users>();
foreach (var u in allEvent.AttendingUsers.Split(',').ToList())
{
users.Add(new Users
{
Id = Convert.ToInt64(u)
});
}
allEvent.Users = users;
The Convert.ToInt64() method is used if you need a long type. But be aware, this could throw an exception.
https://msdn.microsoft.com/en-us/library/0zahhahw(v=vs.110).aspx
FormatException or OverflowException
Upvotes: 1