2009-05-17 55 views
0

这是我编写的代码,但我想使用LINQ,你能帮我把这段代码转换成LINQ吗?将我的SQL转换为LINQ

/// <summary> 
/// Stores the request in the PublisherRequests table and 
/// the selected categories in the PubReq_Categories table. 
/// </summary> 
/// <param name="UserId">The user's ID logged in.</param> 
/// <param name="Url">URL of the site that you want show the banner on it.</param> 
/// <param name="TypeId">The type id of the banner type you want to show.</param> 
/// <param name="CategoryIds">A set of category IDs depend on your banner.</param> 
/// <returns></returns> 

public static int PutRequest(string UserId,string Url,int TypeId,int[] CategoryIds) 
{ 
    int reqId; 

    using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString)) 
    { 
     //Retrieves the last RequestId from database. 
     string selectLastReq = "SELECT TOP 1 RequestId FROM PublisherRequests WHERE UserId=" + 
      UserId.ToString() + "ORDER BY RequestId DESC"; 
     SqlCommand cmdSelect = new SqlCommand(selectLastReq, cnn); 

     //For inserting the new request in the database. 
     string insertRequest = string.Format("INSERT INTO PublisherRequests(" + 
      "RequestId, UserId,PageUrl, TypeId) VALUES ('{0}','{1}',{2})", 
      UserId, Url, TypeId); 
     SqlCommand cmdInsert = new SqlCommand(insertRequest, cnn); 

     //For inserting each category for the request on a new row. 
     string insertReqCat = string.Format("INSERT INTO PubReq_Categories(" + 
      "RequestId, CategoryId) VALUES (@ReqId,@CatId)"); 
     SqlCommand cmdInsertReqCat = new SqlCommand(insertReqCat, cnn); 
     cmdInsertReqCat.Parameters.Add("@ReqId", SqlDbType.Int); 
     cmdInsertReqCat.Parameters.Add("@CatId", SqlDbType.Int); 

     cnn.Open(); 

     //New request insertion. 
     cmdInsert.ExecuteNonQuery(); 

     //Retrieve last request number. 
     reqId = Convert.ToInt32(cmdSelect.ExecuteScalar()); 

     //Categories insertion. 
     cmdInsertReqCat.Parameters["@ReqId"].Value = reqId; 
     foreach (int catId in CategoryIds) 
     { 
      cmdInsertReqCat.Parameters["@CatId"].Value = catId; 
      cmdInsertReqCat.ExecuteNonQuery(); 
     } 
    } 

    return reqId; 
} 

回答

2

假设你正在使用的设计,该请求ID列是自动生成的,你有两个类之间的关联,和你的类如下命名的,我认为这会工作。

using (var context = new DBDataContext()) 
{ 
    var request = new PublisherRequest 
        { 
        UserId = UserId, 
        PageUrl = Url, 
        TypeId = TypeId 
        }; 

    for (var categoryId in CategoryIds) 
    { 
     request.PubReqCategories.Add(new PubReqCategory 
             { 
              CategoryId = categoryId 
             }); 
    } 

    context.PublisherRequests.InsertOnSubmit(request); 
    context.SubmitChanges(); 
}