UNitofWork,编辑方法
本文关键字:方法 编辑 UNitofWork | 更新日期: 2023-09-27 18:20:16
我尝试使用存储库和unitOfWork 编辑用户
这是我的GenericRepository:
public class GenericRepository<TEntity> where TEntity : class
{
internal LolaBikeContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(LolaBikeContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
这是我的作品单位:
public class UnitOfWork : IDisposable
{
private LolaBikeContext context = new LolaBikeContext ();
private GenericRepository<UserProfile> userRepository;
public GenericRepository<UserProfile> UserRepository
{
get
{
if (this.userRepository == null)
{
this.userRepository = new GenericRepository<UserProfile>(context);
}
return userRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
现在我想编辑一个用户,我现在有这样的方法:
[HttpPost]
public ActionResult Edit([Bind(Include="FirstName, LastName")]UserProfile userprofile)
{
try
{
if (ModelState.IsValid)
{
string username = User.Identity.Name;
// Get the userprofile
//UserProfile user = unitOfWork.UserRepository.Get() //db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
unitOfWork.UserRepository.Update(userprofile);
unitOfWork.UserRepository.Insert(userprofile);
//user.FirstName = userprofile.FirstName;
//user.LastName = userprofile.LastName;
//user.Email = userprofile.Email;
//user.Motto = userprofile.Motto;
//user.PlaceOfBirth = userprofile.PlaceOfBirth;
//user.HowManyBikes = userprofile.HowManyBikes;
//user.BesideYourBeth = userprofile.BesideYourBeth;
//user.NicestRide = userprofile.NicestRide;
//user.WorstRide = userprofile.WorstRide;
//user.AmountKmPerYear = userprofile.AmountKmPerYear;
//user.AverageSpeed = userprofile.AverageSpeed;
//user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
//user.PhoneNumber = userprofile.PhoneNumber;
//db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Edit", "Account");
}
}
catch (DataException)
{
ModelState.AddModelError(string.Empty, "Unable to save changes");
}
return View(userprofile);
}
但一切都不会改变。
谢谢
但是如果我用试试
[HttpPost]
public ActionResult Edit(UserProfile userprofile)
{
if (ModelState.IsValid)
{
string username = User.Identity.Name;
// Get the userprofile
// UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
unitOfWork.UserRepository.Update(userprofile);
unitOfWork.UserRepository.Insert(userprofile);
//user.FirstName = userprofile.FirstName;
unitOfWork.Save();
//db.SaveChanges();
return RedirectToAction("Edit", "Account");
}
return View(userprofile);
}
我得到这个错误:
{"Violation of UNIQUE KEY constraint 'UQ__UserProf__C9F28456B1DA0D25'. Cannot insert duplicate key in object 'dbo.UserProfile'. The duplicate key value is (savant).'r'nThe statement has been terminated."}
但是只有一个用户名名为savant
当你写这个:[Bind(Include="FirstName, LastName")]UserProfile userprofile
时,这意味着你的用户配置文件只接受这两个值,你没有ID,所以当你调用Update方法时,dbSet.Attach(entityToUpdate);
不能附加没有ID的实体。你必须从前端转发ID参数。。。或者,您可以通过其他方式获取ID,但关键是没有ID集的元素不能附加。