我尝试使用存储库和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;
}
}
这是我的UnitOfWOrk:
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的用户名
答案 0 :(得分:2)
当你写这个:[Bind(Include="FirstName, LastName")]UserProfile userprofile
时,这意味着你的userprofile只接受这两个值,你没有ID,所以当你进行Update方法调用时,dbSet.Attach(entityToUpdate);
无法附加实体哪个没有ID。您还必须从前端转发ID参数...或者您可以通过其他方式获取ID,但重点是没有ID设置的元素无法附加。