2017-02-21 54 views
0

我有一个名为Repository的类,它处理CSV文件并从分析的值创建对象。存储库将新数据保存到数据库的异步操作

还有就是,在这个类两个列表属性:

public static List<Product> ProductsList { get; set; } 
public static List<Category> CategoriesList { get; set; } 

有一个在它解析发布CSV文件来创建它会被分配给ProductsListCategoriesList的产品和类别列表中的库类的方法分别在方法内部。

public static void CSVToList(HttpPostedFileBase CSVFile){} 

然后是在这个类节省了产品和类别到这些方法的dbContext.Both从控制器中的存储库类的外部被称为另一种方法。

public static void SaveProducts() 
     { 
      foreach(var item in ProductsList) 
      { 
       db.Products.Add(item); 
      } 

      foreach(var item in CategoriesList) 
      { 
       db.Categories.Add(item); 
      } 

      await db.SaveChangesAsync(); 
     } 

当我运行应用程序,并发送一个CSV文件POST请求,我得到这个错误:

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

Source Error: 


Line 348:   { 
Line 349:    Repository.CSVToList(viewModel.CSVFile); 
Line 350:    Repository.SaveProducts(); 
Line 351: 
Line 352:    return RedirectToAction("Index", new { ManageMessageId.DataImportSuccess }); 

Source File: C:\src\smokindonut\Valueville\ValueVille\Controllers\ManageController.cs Line: 350 

我试图使控制器方法是异步任务与来电者资料库保存方法等待:

public async Task<ActionResult> AddCSVData(){ 

     await Repository.SaveProducts(); 
    } 

我也试图让SaveProducts()方法是异步任务,但它始终使方法名称以“异步”开始 - 每次都给出相同的错误。

回答

1

你需要改变你的函数的签名

public static void SaveProducts() 

public async Task SaveProducts() 

您的通话功能,那么需要有一个签名与异步任务,并调用保存功能是这样的:

Task saveTask = SaveProducts(); 
//do some logic 
await saveTask; 
+0

我已经这样做了,现在我得到一个错误,指出“一个或多个实体的验证失败,请参阅EntityValidation错误'属性的更多细节“与代码在同一行:await db.SaveChangesAsync(); 。 – naz786