我的界面将会是
public interface IApplicationDbContext : IDisposable { // Should I add below line? // DbSet<ApplicationUser> User { get;} DbSet<Book> Books { get; } int SaveChanges(); }这种方法的问题是,我失去了对来自IdentityDbContext.Users的用户"的访问权限.
private ApplicationDbContext ctx = new ApplicationDbContext(); ctx.Users.somthing() works但是下面,编译器抱怨
private IApplicationDbContext ctx = new ApplicationDbCOntext(); ctx.Users.something..IApplicationDbContext不包含用户"的定义,也没有扩展方法用户" ...
我想我在这里缺少一个关键的概念.
IApplicationDbContext does not contain a definition for 'Users' and no extensions method 'Users'...
I think I am missing a crucial concept here.
你能帮我吗?
推荐答案如果您将ctx当作IApplicationDbContext的实例,则表示您只希望了解IApplicationDbContext中的那些内容.界面,无论该界面的具体实现是什么.
If you delcare ctx as an instance of IApplicationDbContext you're delcaring your intent that you only wish to know about those things in the IApplicationDbContext interface, regardless of what the concrete implementation of the interface happens to be.
如果您想同时访问IdentityDbContext<ApplicationUser>成员和 IApplicationDbContext成员,则需要删除同时包含这两种类型的类型,例如您的ApplicationDbContext类.
If you want access to both IdentityDbContext<ApplicationUser> members and IApplicationDbContext members, you need to delcare a type which is both of those things, e.g. your ApplicationDbContext class.
或者,最好不要在具体的ApplicationDbContext实现中扩展IdentityDbContext<ApplicationUser>,而应遵循优先考虑组成而不是继承的原则,并允许ApplicationDbContext拥有IdentityDbContext<ApplicationUser>的实例,例如
Alternatively, and preferably, rather than extend IdentityDbContext<ApplicationUser> in your concrete implementation of ApplicationDbContext, you could instead follow the principle of prefering composition over inheritance, and allow ApplicationDbContext to own an instance of IdentityDbContext<ApplicationUser>, e.g.
public class ApplicationDbContext : IApplicationDbContext { private readonly IdentityDbContext<ApplicationUser> _dbContext; public IDbSet<ApplicationUser> Users { get { return _dbContext.Users; } } public ApplicationDbContext(IdentityDbContext<ApplicationUser> dbContext) { _dbContext = dbContext; } public DbSet<Book> Books { get; set; } },如果需要,还可以更改接口定义以提供Users属性.这样,您就可以在隐藏您不需要的信息的同时仍然访问所需的信息.参见
and, if you needed to, alter your interface definition to also provide the Users property. This allows you to still access the information you need, while hiding the information you don't. See
en.wikipedia/wiki/Composition_over_inheritance 和 en.wikipedia/wiki/Information_hiding 了解更多信息.
更多推荐
如何使用ApplicationDbContext制作接口类?
发布评论