I am attempting to use Entity Framework 5 to query an existing MySQL database. I used code-first to create a code-based model that maps to an existing database following this tu
You have one data type that you are calling separate names. That is a little confusing. However To get this to work with code first you just need the following fluent configuration in your Custom DbContext class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<user>().
HasMany(c => c.Buddies).
WithMany().
Map(
m =>
{
m.MapLeftKey("user_id");
m.MapRightKey("buddy_id");
m.ToTable("buddies");
});
}
This assuming your user class looks like this:
[Table("user")]
public class user
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public virtual List<user> Buddies { get; set; }
}
If you use the above method every user object you have will have a navigation property on it called Buddies. When querying for users you will want to eager load buddy users, do:
context.users.Include("Buddies")
Further, To address your issue with multiple readers. It is because you have not enumerated the query (db.users) from your first loop. To address that you can enumerate the query like so:
var users = context.users.Include("Buddies").ToList();
foreach(var user in users)....
And if you use the configuration above, you don't need to try and match id's you simply acquire the list (null field if new) of buddies from the user using the buddies navigation property (virtual,lazy loaded), do:
user.Buddies
As you can see you don't really need a 'Model.buddy' (since it only contains an id mapping) Entity framework will take care of the linking. However if you're not always including the Buddies in your user query you may want the table. Which would be queried with LINQ in the following way:
var userBuddies = db.buddies.Where(buddy=>buddy.user_id == user.id).ToList();
//An enumerated list of user buddies
//do stuff