I have a 2D array of values that can range in size (although, I can make a large, fixed size if needed) that I want to store in a database. Can anyone tell me the best way to do this?
To me a 2D array sounds like (x,y) = somevalue. So I'm thinking of something simple, something like this (assuming somevalue is an int):
public interface IArrayValueEntity
{
int ArrayIndexX { get; set; }
int ArrayIndexY { get; set; }
int Value { get; set; }
}
The entity type implements it like this (or you can have just the implementation if you prefer):
public class ArrayValue : IArrayValueEntity
{
public int ArrayIndexX { get; set; }
public int ArrayIndexY { get; set; }
public int Value { get; set; }
}
Then you can make ArrayIndexX and ArrayIndexY be entity's primary key (and have EF enforce uniqueness of combinations of these two values) in overriding the OnModelCreating method of your DbContext if you're going code-first.
public class MyDbContext : DbContext
{
public IDbSet<ArrayValue> ArrayValues { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// there are several options here...
}
}
If you don't have the database from the start, EF can create it for you (and will by default, if I'm not mistaken), based on how you configure your entities.
And then you can have a service that gets you a value for a given (x,y) key, and/or another that gets you... your 2D array back.
EDIT
To address the 2D array being "part of" a map entity, you merely need to define navigation properties - if you want you can also define a foreign key property:
public class Map : IMapEntity
{
public int Id { get; set; } // primary key
public string Description { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
// Navigation property on the "one" side (note "virtual ICollection")
public virtual ICollection<ArrayValue> ArrayValues { get; set; }
}
public class ArrayValue : IArrayValueEntity
{
public int ArrayIndexX { get; set; }
public int ArrayIndexY { get; set; }
public int Value { get; set; }
// FK property
//public int MapId { get; set; }
// Navigation property on the "many" side (note "virtual")
public virtual Map Map { get; set; }
}
Using the modelBuilder in OnModelCreating or attributes decorating the entity class members, you then configure those relationships:
modelBuilder.Entity<Map>().HasMany(e => e.ArrayValues)
.WithRequired(e => e.Map);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With