views:

122

answers:

2

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?

+1  A: 

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
}
Justin Niessner
@Justin i do have `material` LINQ-to-SQL object... How will be my repository method look like? Please provide me some code..
Pandiya Chendur
@justion i dont want the cast thing... I want to insert using Linq-to-sql object... `Material` has `Id and all other properties`
Pandiya Chendur
@Pandiya Chendu - The Implicit cast will make it so the framework casts the business object as your LINQ-to-SQL Object (therefore inserting the LINQ-to-SQL object appropriately).
Justin Niessner
@justin got your point now...
Pandiya Chendur
A: 

you might want to add db.SubmitChanges() to commit the changes

Sundararajan S