C# ASP.NET MVC'de "InvalidOperationException" hatası

keremgencer

Hectopat
Katılım
7 Mayıs 2021
Mesajlar
239
Çözümler
2
Daha fazla  
Cinsiyet
Erkek
Merhabalar asp.net mvc blog projesi yaparken şu hata ile karşılaştım:

InvalidOperationException: The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

C#:
public IActionResult Create(PostDto p,List<string> categories)
        {
            p.UserId = 1;
            p.User = _userService.GetById(1);

            var cs = new List<CategoryDto>();

            foreach (var category in categories)
            {
                cs.Add(_categoryService.GetById(Convert.ToInt32(category)));
            }
            p.Categories = cs;

            ModelState.Remove("User");
            if (ModelState.IsValid)
            {
                _postService.Insert(p);  

            return RedirectToAction(nameof(Index));
            }
            ViewBag.categories = _categoryService.GetAll();
            return View(p);
        }
C#:
public void Insert(PostDto post)
        {
            _db.Posts.Add(post.DtoToPost());

            _db.SaveChanges();
        }
C#:
public static Post DtoToPost(this PostDto p)
        {
            return new Post { Id = p.Id, Categories = p.Categories.DtoListToCategoryList(),
 Content = p.Content, CreatedAt = p.CreatedAt, DeletedAt = p.DeletedAt, Title = p.Title,
 UpdatedAt = p.UpdatedAt, UserId = p.UserId, User = p.User.DtoToUser() };
        }
public static List<Category> DtoListToCategoryList(this List<CategoryDto> p)
        {
            List<Category> dtos = new List<Category>();
            foreach (var item in p)
            {
                dtos.Add(item.DtoToCategory());
            }
            return dtos;
        }


public static Category DtoToCategory(this CategoryDto c)
        {
            return new Category { Description = c.Description, Name = c.Name, Id = c.Id, Slug = c.Slug };
        }

public static User DtoToUser(this UserDto u)
        {
            return new User { City = u.City, Email = u.Email, Id = u.Id, Name = u.Name, Password = u.Password, Phone = u.Phone };

        }
Bayağı bir acemi olduğumdan kod biraz kirli olabilir. Kusura bakmayın.
(Not: Kod bu kadar değil sadece Post oluşturulurken kullanılan parçaları attım.)
 

Bu konuyu görüntüleyen kullanıcılar

Bu siteyi kullanmak için çerezler gereklidir. Siteyi kullanmaya devam etmek için çerezleri kabul etmelisiniz. Daha Fazlasını Öğren.…