【发布时间】:2014-01-10 17:24:52
【问题描述】:
我有一个 WCF 项目,我使用实体框架 v6 和代码优先生成数据库。 但是我对 User 类和 FeedRss 之间的关系有疑问。我想为每个用户提供几个 FeedRss。我的代码工作(没有例外)但没有添加到 ICollection 提要中(在用户中),在数据库中恢复后这个列表是空的。
public class User
{
[Key]
public int UserID {get; set;}
...
[InverseProperty("User")]
public ICollection<FeedRSS> feeds { get; set; }
public User()
{
feeds = new List<FeedRSS>();
}
}
一个用户->多个 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; } }
我的代码测试函数(但返回一个空列表):
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();
}
我测试了其他非常不同的代码(流畅的API,在FeedRss中强制使用UserId..),但我不明白实体框架中的关系原理......我尝试了几个示例代码都不成功......
*对不起,我的英语大概是这样的
【问题讨论】:
-
可以添加getUser方法的代码吗?我认为您必须在查询中添加一个 Include(p => p.feeds)。
-
完成,我不知道包含。我 rtfm ^^
标签: entity-framework c#-4.0 ef-code-first code-first