Click here to Skip to main content
15,888,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In model I have 3 tables in relation to many many.



My question is how to write data to the OrderPosition table. I understand that I should first write data in the Order and Position table. Then, having two keys from these arrays, I should read them and send them to the OrderPosition as external keys where they will be saved. What should a record of these instructions look like?

What I have tried:

<pre lang="c#"><pre> public class Order
{
    [Key] 
    public int IdOrder { get; set; }
    public string UserId { get; set; }
    public virtual User User { get; set; }
    public int IdOrderAttachment { get; set; }
    public virtual OrderAttachment OrderAttachment { get; set; }
    public virtual ICollection<Employee> Employee { get; set; }

    [Required(ErrorMessage = "Specify the date of order acceptance")]
    [Display(Name = "Date of acceptance of the order")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTimeDateOfAcceptance  { get; set; }
    [Display(Name = "Date of completion planning")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? DateOfCompletionPlanning { get; set; }
    [Display(Name = "End Date")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? EndDate { get; set; }
    [Required(ErrorMessage = "Enter the subject")]
    [MaxLength(200, ErrorMessage = "Name max 200 characters")]
    [Display(Name = "Subject")]
    public string Subject { get; set; }
    public virtual ICollection<OrderPosition> OrderPosition{ get; set; }

public class OrderPosition
    {
        [Key]
        public int IdOrderPosition { get; set; }
        public int IdOrder { get; set; }
        public int IdPosition { get; set; }
        public virtual Order Order { get; set; }
        public virtual Position Position { get; set; }
    }

public class Position 
    {
        [Key]
        public int IdPosition  { get; set; }
        [Column(TypeName = "nvarchar(MAX)")]
        [Display(Name = "Description")]
        [UIHint("tinymce_jquery_full"), AllowHtml]
        public string Description { get; set; }
        public virtual ICollection<OrderPosition> OrderPosition{ get; set; }
    }


 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateOrder(HttpPostedFileBase file, DataOrderUserViewModel viewModel)
    {
        var userId = User.Identity.GetUserId();         

        if (ModelState.IsValid)
        {
            if (file != null && file.ContentLength > 0)
            {
                string path = "/Content/Layout/CompanyFile";
                if (!Directory.Exists(HttpContext.Server.MapPath(path)))
                {
                    Directory.CreateDirectory(HttpContext.Server.MapPath(path));
                }
                string filename = Path.GetFileName(file.FileName);

                file.SaveAs(Path.Combine(HttpContext.Server.MapPath(path), filename));
                viewModel.NameFile = path+ "/" + filename;

                //var nameFile = Path.GetFileName(file.FileName);

                //var path = Path.Combine(Server.MapPath("/Content/Layout/CompanyFile"), nameFile);

                //file.SaveAs(path);

            }

            var order = new Order()
            {
                DateTimeDateOfAcceptance  = viewModel.DateTimeDateOfAcceptance,
                Subject= viewModel.Subject,                 
                UserId = userId

            };

            var position  = new Position ()
            {
                Description = viewModel.Description 
            };

            var orderAttachment = new OrderAttachment ()
            {
                NameFile= viewModel.NameFile,
                Description = viewModel.Description2 
            };

            db.Order.Add(order);
            db.Position.Add(position);
            db.OrderAttachment.Add(orderAttachment);
            db.SaveChanges();

        }
        return RedirectToAction("Index", "Administration");
    }
Posted
Updated 5-Sep-17 6:43am

1 solution

Simple - don't bother with the intermediate class. Just have a collection of Position entities on the Order, and a collection of Order entities on the position. EF will take care of the rest for you.
C#
public class Order
{
    ...
    
    public virtual ICollection<Position> Positions { get; set; }
}

public class Position
{
    ...
    
    public virtual ICollection<Order> Orders { get; set; }
}

...

var order = new Order
{
    DateTimeDateOfAcceptance = viewModel.DateTimeDateOfAcceptance,
    Subject = viewModel.Subject,                 
    UserId = userId,
    
    OrderAttachment = new OrderAttachment
    {
        NameFile = viewModel.NameFile,
        Description = viewModel.Description2,
    },
    
    Positions = new []
    {
        new Position
        {
            Description = viewModel.Description,
        },
    },
};

db.Order.Add(order);
db.SaveChanges();

Configure Many-to-Many Relationship in Code First[^]
 
Share this answer
 
Comments
przemo27ns 8-Sep-17 7:50am    
Thank you very much for your help. It works great.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900