MVC中的多对多关系 - 使用外键写入表 [英] Many to many relationship in MVC - write to a table with foreign keys

查看:140
本文介绍了MVC中的多对多关系 - 使用外键写入表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模特中我有3张桌子与很多人相关。







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



我尝试了什么:



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

推荐答案

简单 - 不要打扰中间类。只需在订单上有 Position 实体的集合,以及订单的集合该职位上的实体。 EF将为您处理剩下的事情。

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.
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();



在Code First中配置多对多关系 [ ^ ]


这篇关于MVC中的多对多关系 - 使用外键写入表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆