实体框架 - 保存更改问题

时间:2017-07-01 09:38:14

标签: c# mysql asp.net entity-framework model-view-controller

我在我的个人博客项目中使用MySQL,MVC + EF6(数据库优先)。 (我是asp,ORM等的新手)。

这是我的数据库架构的一部分。 enter image description here

当我尝试使用方法SaveChanges保存我的文章时,我收到错误。

  

System.Data.Entity.Infrastructure.DbUpdateException。发生错误   同时保存不公开外键属性的实体   他们的关系。 EntityEntries属性将返回null   因为单个实体不能被识别为   例外。保存时可以更轻松地处理异常   在您的实体类型中公开外键属性。见   InnerException以获取详细信息。

的InnerException

  

您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本,以获得正确的语法   靠近'(SELECT \ n article_has_categoryArticle_Id,   \ N article_has_category`Category_I&#39。在第1行

我检查了模型和架构。 (看起来很好)

我的第一个想法是: \ n` 字符"吃掉"其余的SQL命令。 :)但我不确定。

我的"添加"方法是:


    [HttpPost]
    public ActionResult Add(articles article, FormCollection collection)
    {
          UnitOfWork u = new UnitOfWork();                 
          string[] categoryArray = collection["Category"].Split(',');

         int i = 0;
         foreach (string s in categoryArray)
         {
               i++;
               if (s == "true")
               {
                     article_categories c = u.Article_categories.Get(i);
                     article.article_categories.Add(c);
               }
         }                
         article.Autor_Id = 1;
         article.Date = DateTime.Now;
         u.Articles.Add(article);
         u.Complete();  //include saveCanges method
         return View("Index", "Blog");
    }

我的文章课程:


public partial class articles
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public articles()
        {
            this.messages = new HashSet();
            this.article_categories = new HashSet();
        }

        public int Id { get; set; }
        [Required(ErrorMessage = "Titulek je povinný")]
        public string Title { get; set; }

        [AllowHtml]
        public string Perex { get; set; }

        [AllowHtml]
        public string Text { get; set; }
        public System.DateTime Date { get; set; }
        public int Autor_Id { get; set; }
        public string Image_Name { get; set; }

        public virtual users users { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection messages { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection article_categories { get; set; }
    }

感谢您的时间:)

0 个答案:

没有答案