MVC中的多对多关系 - 使用外键写入表

时间:2017-09-05 08:18:38

标签: asp.net-mvc entity-framework asp.net-mvc-5 many-to-many

在模型中,我有3个表与许多表相关。

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");
}

我的问题是如何将数据写入OrderPosition表。 我知道我应该首先在Order and Position表中写入数据。 然后,从这些数组中获取两个键,我应该读取它们并将它们作为外部键发送到OrderPosition,它们将被保存。 这些说明的记录应该是什么样的?

1 个答案:

答案 0 :(得分:0)

我是否需要在我的案例中定义以下关系?

modelBuilder.Entity<OrderPosition>()
       .HasKey(c => new { c.IdOrder , c.IdPosition });

   modelBuilder.Entity<Order>()
       .HasMany(c => c.Subject )
       .WithRequired()
       .HasForeignKey(c => c.IdOrder );

   modelBuilder.Entity<Position>()
       .HasMany(c => c.Description )
       .WithRequired()
       .HasForeignKey(c => c.IdPosition );