【发布时间】:2015-10-30 18:07:41
【问题描述】:
所以,我有这门课
public abstract class Entity<T> : IEntity<T>, IAuditableEntity,ISoftDeletable where T : struct
{
public T Id { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
public string UpdatedBy { get; set; }
public bool Deleted { get; set; }
}
其中,下线允许我创建类似的类
public class User : Entity<int>
{
public string Username { get; set; }
public string Password { get; set; }
public byte LoginTypeId { get; set; }
public virtual LoginType LoginType { get; set; }
}
这将由像这样的存储库操作:
public abstract class Repository<TEntity,TKey> : IRepository<TEntity, TKey> where TEntity : Entity<TKey> where TKey : struct
{
protected DbContext Context;
protected readonly IDbSet<TEntity> Set;
protected Repository(DbContext context)
{
Context = context;
Set = Context.Set<TEntity>();
}
public TEntity Get(TKey key)
{
return Set.FirstOrDefault(o => o.Id.Equals(key));
}
public virtual IEnumerable<TEntity> GetAll()
{
return Set.AsEnumerable();
}
}
目标是这将在某些 WebApi2 控制器中使用,但按照良好的规则规定,我不应该按原样公开 User 类(而且我不允许这样做)。
我的要求是基本属性(Id、Datetime、Deleted 等)在控制器级别变为只读,但在存储库级别显然是读/写。
例如,控制器不能直接设置 Deleted 属性,但必须在调用 Delete 操作时由存储库设置。
我可以隐藏继承的属性,但我不能禁止任何人这样做
var u= new User();
var baseEntity = (Entity<int>) u;
那么,如何在控制器级别将带有基本属性的用户实体设置为只读?
【问题讨论】:
-
为什么不将控制器不应该访问的属性设置为受保护,然后为它们添加get方法?
标签: c# .net asp.net-mvc inheritance asp.net-web-api2