EF6 CodeFirst One to Many MySQL a foreign key constraint fails

岁酱吖の 提交于 2019-12-08 09:06:25

问题


I'm doing a Mapping from existing Database to CodeFirst and I'm having a problem with One To Many Relationships.

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity. Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Cannot add or update a child row: a foreign key constraint fails

I have a T_USER entity like this.

public partial class T_USER{

    public T_USER(){
        this.T_OBJECTS = new HashSet<T_OBJECTS> ();
        this.T_OBJECTS1 = new HashSet<T_OBJECTS> ();
    }

    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public virtual ICollection <T_OBJECT> T_OBJECTS { get; set; }

    public virtual ICollection <T_OBJECT> T_OBJECTS1 { get; set; }
}

Also I have my T_OBJECT entity like this.

public partial class T_OBJECT (){

    [Key]
    public int ID { get; set; }

    [Required]
    public int USER1 { get; set; }

    [Required]
    public int USER2 { get; set; }

    [ForeignKey("USER1")]
    public virtual T_USER T_USER1 { get; set; }

    [ForeignKey("USER2")]
    public virtual T_USER T_USER2 { get; set; }
}

With this DataAnnotations I have a DBUpdateException "Unknown Column T_USER_OID in field list"

I have discovered that if my Database field names doesn't follow the Code First Conventions I have to use the Fluent API for One To Many Relationships and I have coded like this.

public class T_OBJECT_Map : EntityTypeConfiguration <T_OBJECTS>
    {
        public T_OBJECT_Map()
        {
            this.HasRequired<T_USER>(M => M.T_USER)
                .WithMany(U => U.T_OBJECTS)
                .HasForeignKey(M => M.USER1);

            this.HasRequired<T_USER>(M => M.T_USER1)
                .WithMany(U => U.T_OBJECTS1)
                .HasForeignKey(M => M.USER2);
        }
    }

With this code I have the exception that I have mentioned at the beginning of this question.

I have also try to set the DBInitializer to null using this code to prevent the EF try to write in the Database but it fails with the same Exception

Database.SetInitializer<Context>(null);

来源:https://stackoverflow.com/questions/32611449/ef6-codefirst-one-to-many-mysql-a-foreign-key-constraint-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!