将方法添加到类DbSet <tentity>

时间:2016-03-06 14:59:32

标签: c# asp.net-mvc-5

我正在使用asp.net mvc 5,并希望为类Topic实现3种方法(添加/更新/删除):

class Topic : IDisposable
{
        public Topic() { }
        private TopicViewModels Model { get; set; }
        private string Flag { get; set; }

        public void Add(TopicViewModels model)
        {
            Model = model;
            Flag = "Add";
        }

        public void Update(TopicViewModels model)
        {
            Model = model;
            Flag = "Update";
        }

        public void Remove(TopicViewModels model)
        {
            Model = model;
            Flag = "Remove";
        }

        public async Task<int> SaveChangesAsync()
        {
            using (var db = new MyDbContext())
            {
                switch (Flag)
                {
                    case "Add":
                        db.Topics.Add(Model);
                        break;
                    case "Update":
                        var topic = await db.Topics.SingleAsync(x => x.Id == Model.Id);    
                        topic = Model;
                        break;
                    case "Remove":
                        db.Topics.Remove(Model);
                        break;
                }
                return await db.SaveChangesAsync();
            }
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
}

我的问题:如何声明方法

public virtual TEntity Update(TEntity entity); 
课程DbSet<TEntity>中的

“更新”时我想要实现的目标:

switch (Flag)
{
    case "Update":
        db.Topics.Update(Model);
        break;
}

我的子问题:还有另一种方法可以在不使用标志的情况下完全调用方法SaveChangesAsync吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做;

public void Update<T>(T entity) where T:class
{
        db.Entry<T>(entity).State = EntityState.Modified;
        db.SaveChanges();
}