當我嘗試通過使用CaseRepository.cs中的bool方法添加一個案例時,通過將用戶分配給case對象來確定哪個用戶是案例的所有者(誰創建它?),但是當我嘗試添加案例時分配它然後它試圖添加一個新的用戶對象的表,雖然它是一個現有的用戶我傳入參數?EF - 嘗試添加新對象而不是使用現有的?
簡而言之:我試圖讓用戶創建一個案例並將該案例分配給用戶。
將MembershipUser映射到User對象的原因是爲了使EF(代碼優先)能夠將其用於CRUD操作。
// CaseController.cs
[AuthWhere(AuthorizeRole.Developer)]
[HttpPost]
public ActionResult Create(CreateCaseViewModel model)
{
var success = false;
string message;
User user = Mapper.Map<MembershipUser, User>(_membershipService.GetUserByUserName(User.Identity.Name));
Case createCase = _caseService.CreateCase(model.Topic, model.Message);
bool addCase = _caseService.AddCase(createCase, user);
if(!addCase)
{
message = ControllerResources.CaseCreateFail;
}
else
{
success = true;
message = ControllerResources.CaseCreateSuccess;
}
return Json(new
{
Success = success,
Message = message,
Partial = RenderPartialViewToString("List", GetCases)
});
}
// RepositoryBase.cs
public class RepositoryBase<T> : IRepository<T> where T : class
{
public IDbContext Context { get; private set; }
public IDbSet<T> ObjectSet { get; private set; }
public RepositoryBase(IDbContext context)
{
Contract.Requires(context != null);
Context = context;
if (context != null)
{
ObjectSet = Context.CreateDbSet<T>();
if (ObjectSet == null)
{
throw new InvalidOperationException();
}
}
}
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(Context != null);
Contract.Invariant(ObjectSet != null);
}
public IRepository<T> Add(T entity)
{
ObjectSet.Add(entity);
return this;
}
public IRepository<T> SaveChanges()
{
Context.SaveChanges();
return this;
}
}
// CaseRepository.cs
public class CaseRepository : RepositoryBase<Case>, ICaseRepository
{
public CaseRepository(IDbContext context)
: base(context)
{
Contract.Requires(context != null);
}
public bool AddCase(Case @case, User user)
{
@case.User = user;
ObjectSet.Add(@case);
Context.SaveChanges();
return true;
}
}
在http://www.codeproject.com/Articles/318820/ASP-NET-MVC-3-0-JqGrid-Unit-Of-Work-Repository-EF和http:// weblogs中描述的類似的類。 asp.net/dwahlin/archive/2012/03/04/new-pluralsight-course-building-asp-net-mvc-apps-with-ef-code-first-html5-and-jquery.aspx – 2012-05-13 01:00:45