M
M
Mozzarella2018-01-27 18:50:08
SQL
Mozzarella, 2018-01-27 18:50:08

How to fix "Cannot insert explicit value for identity column" error?

There are two entities

public class Sub
    {
        public int SubId { get; set; }
        public string Name { get; set; }
        public SubType Type { get; set; }
        public int Priority { get; set; }
        public int SupGroupId { get; set; }
        public virtual SubGroup SubGroup { get; set; }
        public enum SubType { TextBox,TextArea,Image};
    }

public class SubGroup
    {
        public int SubGroupId { get; set; }
        public string Name { get; set; }
        public Type ForType { get; set; }
        public int Priority { get; set; }
        public virtual ICollection<Sub> Sub { get; set; }

        public enum Type
        {
            [Display(Name = "Отзывы")]
            Review,
            [Display(Name = "Предложения")]
            Application,
            [Display(Name = "Страницы")]
            Page,
            [Display(Name = "Организации")]
            Organization,
            [Display(Name = "Тендеры")]
            Tender,
            [Display(Name = "Тендеры")]
            Offer,
            [Display(Name = "Комментарии")]
            Comment,
            [Display(Name = "Посты")]
            Post
        }
    }

Adding SubGroup to DbSet happens without error. But when setting the SubGroup property on the Sub model, the following Exception is thrown
5a6c9f8ea1e21047160261.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rinat Gilmanov, 2018-01-29
@RinatG

on each auto-incrementing (by means of subd) field, you must add the [DatabaseGenerated (DatabaseGeneratedOption.Identity)] attribute
for one for all primary key fields, put the [Key] attribute

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question