Hello everybody,
I'm quite newbie to EntityFramework and I have encountered a problem, when I add multiple items to database.
This is not the real application, but for learning purposes I have created a test app, that kinda simulate the behaviour of the real application.
The real application is based on producer-consumer pattern, where the consumer saves the received array of bytes somewhere - with some metadata -, which is created upon user interaction, so I don't know when and how many comes.
To simulate this pattern, this is the code I created:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string filename = @"path-to-a-jpg";
byte[] data = System.Drawing.Image.FromFile(filename).ToByteArray();
Visitor someone;
for (int i = 0; i < 100; i++)
{
using (ZooContext ctx = new ZooContext())
{
someone = new Visitor()
{
Name = "test100 " + i,
Img = data
};
ctx.Visitors.Add(someone);
ctx.SaveChanges();
someone = null;
}
GC.Collect();
}
}
Class, that is stored in the DB (it would be nice, to keep the lazy loading enabled):
public class Visitor
{
public int ID { get; set; }
public string Name { get; set; }
public byte[] Img { get; set; }
public virtual ICollection<Animal> FavouriteAnimals { get; set; }
}
My DbContext is this class:
public class ZooContext : DbContext
{
public ZooContext()
{
Database.SetInitializer<ZooContext>(new System.Data.Entity.NullDatabaseInitializer<ZooContext>());
}
public DbSet<Animal> Animals { get; set; }
public DbSet<Visitor> Visitors { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Visitor>()
.HasMany(v => v.FavouriteAnimals)
.WithMany(a => a.Visitors)
.Map(m =>
{
m.MapLeftKey("Visitor_ID");
m.MapRightKey("Animal_ID");
m.ToTable("Visitor_Animal");
});
base.OnModelCreating(modelBuilder);
}
}
After adding approx. 80 items it throws an OutOfMemory exception and at that point the task manager shows around 1200 megabytes of used memory, for vshost process containing my application.
I'm testing it on a 32-bit computer with 3GBs of RAM, but I suppose that the memory overhead should be much more less.
By the way, retrieving from such a huge DB is OK, because it's OK for me, that the retrieved objects are not tracked and querying for images has little memory overhead even, my DB is around 11GB now :).
I forgot to add, that I'm using SQLite with System.Data.SQLite provider.
Thanks in advance! I appreciate any suggestion.