简体   繁体   English

在 Entity Framework Core 中出错

[英]Getting an error in Entity Framework Core

EF Core : what can I do if I get this error in the project I am working on: EF Core:如果我在我正在处理的项目中遇到此错误,我该怎么办:

MySqlException: Duplicate entry '2' for key 'customers.IX_Customers_UserID' MySqlException: 键“customers.IX_Customers_UserID”的重复条目“2”

UserID causes this error when it is present - I do not understand exactly what the error is, please help UserID出现此错误时会导致此错误 - 我不明白错误究竟是什么,请帮忙

public class Context : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Address> Addresses { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //optionsBuilder.UseSqlite("Data Source = Shop.db");
        //optionsBuilder.UseSqlServer(@"Data Source = (localdb)\v11.0; Initial Catalog=ShopDb; Integrated Security = SSPI;");
        optionsBuilder.UseMySql(@"server=localhost;port=3306;database=ShopDb1;user=root;password=admin123;");
    }

    public Context()
    {
        Database.EnsureCreated();
    }
}

public class User
{
    public int ID { get; set; }

    public string UserName { get; set; }
    public string Email { get; set; }

    public Customer Customer { get; set; }
    public List<Address> Addresses { get; set; }
}

public class Customer
{
    public int ID { get; set; }

    public int IdentifyNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public User User { get; set; }
    public int UserID { get; set; }
}

public class Supplier
{
    public int ID { get; set; }

    public string Name { get; set; }
    public string TaxNumber { get; set; }
}

public class Address
{
    public int ID { get; set; }

    public string FullName { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public User User { get; set; }
    public int UserID { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    [MaxLength(100)]
    [Required]
    public string Name { get; set; }

    public decimal Price { get; set; }

    public int CategoryID { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }
    [MaxLength(100)]
    [Required]
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var db = new Context())
        {
            var customer = new Customer()
            {
                 IdentifyNumber = 123,
                 FirstName = "Remzi",
                 LastName = "Balakishiyev",
                 User = db.Users.FirstOrDefault(x => x.ID == 2)
            };

            db.Customers.Add(customer);
            db.SaveChanges();
        }
        Console.ReadLine();
    }

    static void InsertUsers()
    {
        var users = new List<User> {
            new User() { UserName ="Remzi",Email = "remzi.balakisiyev@gmail.com"},
            new User() { UserName ="Xezri",Email = "xezri.balakisiyev@gmail.com"},
            new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva@gmail.com"}
        };
        using (var db = new Context())
        {
            db.Users.AddRange(users);
            db.SaveChanges();
        }
    }

    static void InsertAddresses()
    {
        var addresses = new List<Address> {
           new Address() { FullName = "Remzi Balakisiyev", Title = "Ev addressi", Body = "Masalli", UserID = 1 },
           new Address() { FullName = "Remzi Balakisiyev", Title = "Ish addressi", Body = "Baki", UserID = 1 },
           new Address() { FullName = "Xezri Balakisiyev", Title = "Ev addressi", Body = "Masalli", UserID = 2 },
           new Address() { FullName = "Nurane Tarverdiyeva", Title = "Ev addressi", Body = "Naxcivvan", UserID = 3},
           new Address() { FullName = "Rena Heyderova", Title = "Ev addressi", Body = "Xachmaz", UserID = 2 },
           new Address() { FullName = "Memmed Bedelov", Title = "Ev addressi", Body = "Sumqayit", UserID = 1 }
        };

        using (var db = new Context())
        {
            db.Addresses.AddRange(addresses);
            db.SaveChanges();
            Console.WriteLine("Ishledi");
        }
    }
}

Your problem most probably is running on these lines of code:您的问题很可能在这些代码行上运行:

var users = new List<User> {
    new User() { UserName ="Remzi",Email = "remzi.balakisiyev@gmail.com"},
    new User() { UserName ="Xezri",Email = "xezri.balakisiyev@gmail.com"},
    new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva@gmail.com"}
};
using (var db = new Context())
{
    db.Users.AddRange(users);
    db.SaveChanges(); // ERROR happening here, when trying to insert Users
}

The error is happening because you have put a unique PRIMARY Key constraint over the UserId column.发生错误是因为您在UserId列上放置了唯一的 PRIMARY Key 约束。

Try adding the following attribute over the ID, to fix the issue:尝试在 ID 上添加以下属性,以解决问题:

public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    ...
}

Another note, I think the UserId property redundant in your Customer class.另一个注意事项,我认为UserId属性在您的Customer类中是多余的。

Please also check that if your User⟶Customer relations are defined as one-to-many, then in your Customer class you have to define a collection of Users but not a single User :还请检查您的 User⟶Customer 关系是否定义为一对多,那么在您的Customer类中,您必须定义一组Users而不是单个User

public class Customer 
{
   ...
   public ICollection<User> Users { get; set; }
}

For more information check here .欲了解更多信息,请点击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在实体框架核心的多对多关系中获取导航属性时出错 - Error in getting navigation property in a many to many relationship in entity framework core 重新运行更新迁移时实体框架核心出现错误 - Entity Framework core getting error when rerunning the Update Migration ASP.NET Core Web API &amp; Entity Framework Core; 为什么我收到这个错误? - ASP.NET Core Web API & Entity Framework Core; why am I getting this error? 获取Entity Framework核心1.1的空例外 - Getting Null Exception for Entity Framework core 1.1 Entity Framework Core:获取行的循环参考 - Entity Framework Core: Loop reference on getting rows 使用Entity Framework Core获取动态列 - Getting Dynamic Columns with Entity Framework Core 更新实体框架时出错 - Getting Error On Updating Entity Framework .Net Core 5 Rest Api 实体框架 Linq 从 Z9EBA623737023BF782 获取记录列表时出现表达式翻译错误 - .Net Core 5 Rest Api Entity Framework Linq Expression Translation Error While Getting Record List From Controller 尝试在 Entity Framework Core 中查询表时出现无效列错误 - Getting invalid column error when trying to query table in Entity Framework Core Entity Framework Core - 构建迁移并得到不清楚的错误,说我添加了两次属性 - Entity Framework Core - building a migration and getting unclear error saying I am adding a property twice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM