I have a WCF project and I generate the database with Entity framework v6 and code-first. But I have a problem with the relation between the class User and FeedRss. I want several FeedRss for each User. My code work (no exception) but don't add in the ICollection feeds (in user), this list is empty after the recovery in the database.
public class User
{
[Key]
public int UserID {get; set;}
...
[InverseProperty("User")]
public ICollection<FeedRSS> feeds { get; set; }
public User()
{
feeds = new List<FeedRSS>();
}
}
one user->many feedRss
public class FeedRSS
{
[Key]
public int ID { get; set; }
...
public int UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public FeedRSS()
{
}
}
public class UsersContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<FeedRSS> Feeds { get; set; } }
My function for test my code (but return a empty list) :
public User getUser(int Id)
{
using (UsersContext context = new UsersContext())
{
return context.Users.ToList().Find(
delegate(User u) {
return u.UserID == Id;
});
}
}
public List<FeedRSS> getFeedListTest(User u)
{
using (UsersContext ctx = new UsersContext())
{
User user = ctx.Users.First(i => i.UserID == u.UserID);
FeedRSS f = new FeedRSS() { name = "code", link = "uri" };
user.feeds.Add(f);
//the list user.feeds lenght is = 1
ctx.SaveChanges();
//update working
}
//get the same user in the database but the list uuu.feeds lenght is 0 :(
User uuu = this.getUser(u.UserID);
return uuu.feeds.ToList();
}
I tested other code very different (fluent API, force the UserId in FeedRss..) but I do not understand the principle of the relation in entity framework... I tried unsuccessfully several examples code...
*And sorry for my approximate English