Using the following classes by convention EF will create the tables and PK/FK associations correctly. However when i add data the to photos collection and save the entities the data in the Photos table is not saved to the database table.
I’ m avoiding using any collection types which inherits from ICollection for the public property and instead used a private backing field as i want to control access to Add/Remove methods. Is there anything additional i need to add to the OnModelCreating to tell EF that there’s data in IEnumerable Photos and persist it?
(Data from the Album class can be saved correctly)
public class Album
{
private readonly ICollection<Photo> _photos = new List<Photo>();
public Guid Id {get; set;}
public string Name {get; set;}
public virtual IEnumerable<Photo> Photos
{
get{ return _photos;}
}
public void AddPhoto(byte[] bytes, string name)
{
//some biz rules
Photo p = new Photo();
p.Bytes = bytes;
p.Name = name;
_photos.Add(p);
}
}
public class Photo
{
public Guid Id {get; set;}
public string Name {get; set;}
public byte[] Bytes {get; set;}
}
public class AlbumDbContext : DbContext
{
public AlbumDbContext()
{
this.Database.CreateIfNotExists();
}
public DbSet<Album> Albums { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
I even wonder that tables and relations are correctly created especially when none of your entities have defined key and context doesn’t define set for
Photos. AnywayICollection<T>is a must. Your class is not valid entity and even if you somehow make it work I expect that you will have troubles to use it – for example you can forget about lazy loading.Also handling it this way doesn’t make sense because anybody can convert your enumerable back to collection. You must make enumerable copy of the collection to make it work as supposed.
The only way which can perhaps work is:
And your context will look like:
This solution is pretty ugly because it makes your entity dependent on entity framework.