我正在尝试学习asp.net核心,我正在尝试实现像网站这样的reddit。
我想要做的是当调用subreddit时,我想加载管理员和特定subreddit的成员并将它们传递给viewmodel。
实现这一点我已经制作了两个表
public class MemberSubReddit
{
public long SubRedditId { get; set; }
public virtual SubReddit SubReddit { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
// the names differ since I was trying to check if the problem is from naming conventions
public class AdminSubReddit
{
public long SubRedditId { get; set; }
public virtual SubReddit SubReddit { get; set; }
public string AspNetUsersId { get; set; }
public virtual ApplicationUser AspNetUsers { get; set; }
}
现在当我执行以下代码时:
var sub = _subRedditRepository.GetSingle(e => e.Name == name, s => s.Posts, s => s.Admins, s => s.Members);
SubRedditId和SubReddit对象在管理员和成员中加载,但对于User对象,仅加载UserId(AspNetUserId)并且不加载ApplicationUser。
这也是我的模型构建器代码(基于实体框架核心中的asp.net核心网站,不会自动处理多对多连接,你必须手动完成):
modelBuilder.Entity<AdminSubReddit>()
.HasKey(t => new { t.SubRedditId, t.AspNetUsersId });
modelBuilder.Entity<MemberSubReddit>()
.HasKey(t => new { t.SubRedditId, t.UserId });
modelBuilder.Entity<MemberSubReddit>()
.HasOne(us => us.ApplicationUser)
.WithMany(ms => ms.MemberIn)
.HasForeignKey(us => us.UserId);
modelBuilder.Entity<MemberSubReddit>()
.HasOne(ms => ms.SubReddit)
.WithMany(ms => ms.Members)
.HasForeignKey(ms => ms.SubRedditId);
modelBuilder.Entity<AdminSubReddit>()
.HasOne(us => us.AspNetUsers)
.WithMany(ms => ms.AdminIn)
.HasForeignKey(us => us.AspNetUsersId);
modelBuilder.Entity<AdminSubReddit>()
.HasOne(ms => ms.SubReddit)
.WithMany(ms => ms.Admins)
.HasForeignKey(ms => ms.SubRedditId);
所以请告诉我我做错了什么:D 因为我是新手,如果你能看到代码的任何结构问题,如果你指出它我会很高兴。
修改
public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _context.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.Where(predicate).FirstOrDefault();
}
这是在控制器中调用的方法