C# EF不';无法保存或获取数据
您好,我有以下代码: 这是控制器中的操作C# EF不';无法保存或获取数据,c#,entity-framework,C#,Entity Framework,您好,我有以下代码: 这是控制器中的操作 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Category category) { string currentUserId = User.Identity.GetUserId(); var currentCategory = CategoriesService.GetCategory(category.Id, curr
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Category category)
{
string currentUserId = User.Identity.GetUserId();
var currentCategory = CategoriesService.GetCategory(category.Id, currentUserId);
if (currentCategory != null)
{
currentCategory.Name = category.Name;
CategoriesService.SaveCategory();
}
else
{
Category toAdd = new Category();
toAdd.Name = category.Name;
toAdd.Owner = ApplicationUsersService.GetUser(currentUserId);
CategoriesService.SaveCategory(toAdd);
}
return this.PartialView("_CategoriesListPartial", CategoriesService.GetCategories(currentUserId));
}
这就是我用来将数据保存到数据库的服务
public void SaveCategory()
{
Context.SaveChanges();
}
public void SaveCategory(Category category)
{
Context.Categories.Add(category);
Context.SaveChanges();
}
在我使用currentCategory!=null
一切正常,但在另一个数据库中,模型没有保存
另一个服务类也存在类似问题
这个很好用
public ActionResult Index()
{
string currentUserId = User.Identity.GetUserId();
CategoryViewModel categoriesViewModel = new CategoryViewModel();
categoriesViewModel.Categories = CategoriesService.GetCategories(currentUserId);
return View(categoriesViewModel);
}
服务
public ICollection<Category> GetCategories(string userId)
{
return this.Context.Categories.Where(c => c.Owner.Id == userId && c.IsDeleted == false).OrderBy(c => c.Name).ToList();
}
public ICollection<Book> GetBooks(string userId)
{
return this.Context.Books.Where(b => b.Owner.Id == userId && b.IsDeleted == false).OrderBy(b => b.Name).ToList();
}
服务
public ICollection<Category> GetCategories(string userId)
{
return this.Context.Categories.Where(c => c.Owner.Id == userId && c.IsDeleted == false).OrderBy(c => c.Name).ToList();
}
public ICollection<Book> GetBooks(string userId)
{
return this.Context.Books.Where(b => b.Owner.Id == userId && b.IsDeleted == false).OrderBy(b => b.Name).ToList();
}
public ICollection GetBooks(字符串userId)
{
返回this.Context.Books.Where(b=>b.Owner.Id==userId&&b.IsDeleted==false);
}
请帮助如果不在现场查看
GetCategory()
,这里的内容还不够。但是,我要冒险:在GetCategory()
中使用的上下文实例与在SaveCategory()
中使用的实例不同,请一次问一个问题。只需用GetBooks()修复了这个问题。将数据保存到上下文的问题仍然存在。您确定上下文是正确的对象吗?高亮显示表明它是一个类而不是一个对象。总之,短期上下文通常比长期上下文更好。我有一个基类DbService,它保存EF上下文。它由其他服务类继承,这些服务类提供获取数据并将数据保存到上下文的逻辑。管制员:服务部:我真的看不出有什么问题。你试过对数据库进行验收测试吗?你好。似乎DB或PC出现了局部问题。重新启动系统时,一切正常。无论如何谢谢Sokay开始怀疑这是否是本地问题。不需要“空”接受——因为这本质上是一个临时问题,我建议删除您的问题。我的背上没有皮。