Andrey Pesoshin
Andrey Pesoshin

Reputation: 1186

Entity Framework relations and AutoDetectChanges=false issue

My goal is to have massive insert/update operation implemented. The domain model consists of Image entity related to Folder entity as many-to-one.

Normally I add an image to the db context this way:

var folder = dbContext.Folders.First();

var image = new Image();
image.Folder = folder;
image.<SomeFields> = "<SomeData>";

dbContext.Images.Add(image);
dbContext.SaveChanges();

In order to have better performance I turn off automatic changes tracking:

dbContext.Configuration.AutoDetectChangesEnabled = false;

And now I get an error:

Entities in 'DbContext.Images' participate in the 'Image_Folder' relationship. 0 related 'Image_Folder_Target' were found. 1 'Image_Folder_Target' is expected.

I tried to use:

folder.Images.Add(image);
dbContext.Entry(folder).State = EntityState.Modified;

but it didn't help.

How should I fix an error?

UPD: fixed code snippet

UPD2: Simplified entities (removed inheritance from the base class (to make the code more readable) and most of needless attributes):

Image.cs

public class Image
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string AuthorName { get; set; }

    public string AuthorUrl { get; set; }

    [StringLength(255)]
    [Required]
    [Column(TypeName = "VARCHAR")]
    public new string File { get; set; }

    [Required]
    public bool IsCover { get; set; }

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

    public virtual Product Product { get; set; }

    [Required]
    public virtual Folder Folder { get; set; }

    public override string ToString()
    {
        return File;
    }

    public Image()
    {
        Order = 1;
    }
}

Folder.cs

public class Folder
{
    public int Id { get; set; }

    public virtual Folder Parent { get; set; }
    public virtual ICollection<Image> Images { get; set; }
    public virtual ICollection<Folder> Folders { get; set; }

    public string Name { get; set; }

    public override string ToString()
    {
        return Name;
    }

    public Folder()
    {
        Images = new HashSet<Image>();
    }
}

Upvotes: 1

Views: 165

Answers (1)

Mohammad Akbari
Mohammad Akbari

Reputation: 4766

I test your code, no exception occur, but no data inserted into database. Try this, replace **** code

dbContext.Configuration.AutoDetectChangesEnabled = false;
var folder = dbContext.Folders.First();

var image = new Image();
image.Folder = folder;
image.<SomeFields> = "<SomeData>";

**dbContext.Entry(image).State = EntityState.Added; **

dbContext.SaveChanges();

Upvotes: 1

Related Questions