如何使用ApplicationDbContext制作接口类? [英] How to make an interface class out of ApplicationDbContext?
问题描述
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>,
IApplicationDbContext
{
public ApplicationDbContext()
: base("AppContext")
{
}
// Should I add below line? without any unwanted behavior?
// public DbSet<ApplicationUser> User { get; set;}
public DbSet<Book> Books { get; set; }
}
我的界面将会是
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
http://en.wikipedia.org/wiki/Composition_over_inheritance 和 http://en.wikipedia.org/wiki/Information_hiding 了解更多信息.
这篇关于如何使用ApplicationDbContext制作接口类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!