我正在使用具有自己的上下文的标识。如何正确实现其他实体对身份用户的引用?
public class ApplicationUser : IdentityUser {
// some custom fields
}
public class IdentityContext : IdentityDbContext<ApplicationUser> {
//...
}
我也有一些其他的东西,例如这个
public class Comment{
public int Id {get;set;}
public string Message{get;set;}
public DateTime Time{get;set;}
}
这是由我的其他方面
public class MyContext :DbContext {
public DbSet<Comment> Comments { get; set; }
//... other DbSets
}
问题使用
。我想,我的评论实体有author属性,所以我有这样的事情
public class Comment{
public int Id {get;set;}
public string Message{get;set;}
public DateTime Time{get;set;}
public virtual ApplicationUser Author {get;set;}
}
但ApplicationUser位于不同的背景下,虽然在同一个数据库中。我敢打赌这是不可能的。
如何正确执行此操作? 我应该移动DbSets从MyContext到IdentityContext,这样我就可以自由地使用这样的代码
public virtual ApplicationUser Author {get;set;}
或者我应该把它在不同的上下文,但添加类似
public string AuthorId {get;set}
,并提出一些解决方法每次需要时从不同的上下文中获取作者信息?或者是其他东西?
感谢
编辑
好吧,我结束了这样的事情:
public class ApplicationUser : IdentityUser {
public virtual UserProfile UserProfile { get; set; }
}
public class UserProfile {
[Key, ForeignKey("ApplicationUser")]
public string Id { get; set; }
//... custom fields
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class IdentityContext : IdentityDbContext<ApplicationUser> {
//...
public DbSet<UserProfile> UserProfiles { get; set; }
}
但是我应该如何实现评论的作者引用?喜欢这个?所以它不会通过EF关系链接,我只需在自己的代码中填充UserProfileId?
public class Comment{
public int Id {get;set;}
public string UserProfileId{get;set;}
}
这是正确的方法吗?
编辑该问题。你能再次看到代码吗?您的评论确实有道理,但我仍然不太了解如何将评论类实体与UserProfile链接起来。 – uturupu
谢谢。这可能是我想要的。所以我只要创建用户就设置ApplicationUserId。 – uturupu
不客气。请注意,你将需要这两个上下文。确保ApplicationUser和Person都被创建。您可以选择自己设置标识或使用ApplicationUser生成的标识。无论哪种方式使用该值Person.ApllicationUserId。 –