Search code examples
asp.net-mvcinsertformcollection

what is wrong with this insert method in asp.net mvc?


My controller calls a repository class method on insert,

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude = "Id")]FormCollection collection)
        {
            try
            {
                MaterialsObj materialsObj = new MaterialsObj();
                materialsObj.Mat_Name = collection["Mat_Name"];
                materialsObj.Mes_Id = Convert.ToInt64(collection["MeasurementType"]);
                materialsObj.Mes_Name = collection["Mat_Type"];
                materialsObj.CreatedDate = System.DateTime.Now;
                materialsObj.CreatedBy = Convert.ToInt64(1);
                materialsObj.IsDeleted = Convert.ToInt64(1);
                consRepository.createMaterials(materialsObj);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

and my repository class has this,

public MaterialsObj createMaterials(MaterialsObj materialsObj)
{
    db.Materials.InsertOnSubmit(materialsObj);
    return materialsObj;
}

But when i compile this i get The best overloaded method match for 'System.Data.Linq.Table<CrMVC.Models.Material>.InsertOnSubmit(CrMVC.Models.Material)' has some invalid arguments... cannot convert from 'CrMVC.BusinessObjects.MaterialsObj' to 'CrMVC.Models.Material'..

am i missing something?


Solution

  • The object you pass to InsertOnSubmit has to be one of your LINQ-to-SQL Classes.

    In this case, you're trying to insert an Object of a type that LINQ-to-SQL has no idea about (one of your business objects, not a LINQ-to-SQL type).

    There are several ways to overcome this. Once is to convert the business object to the appropriate LINQ-to-SQL class in your Repository. The other is to create an implicit cast between the two and let .NET handle the rest.

    Repository Cast Code

    public MaterialsObj createMaterials(MaterialsObj materialsObj)
    {
        CrMVC.Models.Material mat = new CrMVC.Models.Material();
    
        // copy properties to the Materials object from materialsObj
        db.Materials.InsertOnSubmit(mat);
    
        materialsObject.IdField = mat.IdField;
    
        return materialsObj;
    }
    

    Implicit Cast Code (method added to the Business Object class)

    public static implicit operator CrMVC.Models.Material
        (CrMVC.BusinessObjects.MaterialsObj)
    {
        // Add conversion code here
    }