mic mic - 1 month ago 12
ASP.NET (C#) Question

insert one to many code first

i want insert factor in db and any factor have customer Id.

i have two class

public class Customer
{

[Key, ForeignKey("Factor")]
public int Id { get; set; }

[Required]
public string Name { get; set; }

[Required]
public string LastName { get; set; }

public Gender Gender { get; set; }

[Required]
public string Mobile { get; set; }

public virtual ICollection<Factor> Factor { get; set; }

}

public class Factor
{
public int ID { get; set; }

[Required]
public string Name { get; set; }

public DateTime Date { get; set; }

public virtual Customer Customer { get; set; }

public virtual ICollection<FactorDetails> FactorDetails { get; set; }

public virtual FactorType FactorType { get; set; }

}


and i create modelview for these two classes,

public class CreateFactorViewModel
{
public Factor Factor { get; set; }
public int CustomerId { get; set; }
}


in create view i add new factor and select one customer from dropdown list.
in create controller i want add CustomerId to factor customer Id

public ActionResult Create(CreateFactorViewModel model)
{

if (ModelState.IsValid)
{
model.Factor.Customer = new Customer { Id = model.CustomerId };

db.Factors.Add(model.Factor);

db.SaveChanges();
return RedirectToAction("Index");
}

return View();
}


but i get this error


Validation failed for one or more entities. See
'EntityValidationErrors' property for more details.


i know this error occurred from customer attribute,but i don't know
how i can inset factor base customer Id.

can you help me?

Answer

from user question, you should declare a ForeignKey

change the class from this code

    public class Factor
    {
        ...
        [ForeignKey("Customer")]
        public int Customer_Id { get; set; }
        ...
}

  public ActionResult Create(CreateFactorViewModel model)
    {

        if (ModelState.IsValid)
        {
             model.Factor.Customer_Id = model.CustomerId;

             db.Factors.Add(model.Factor);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View();
    }