How to model this relationship efficiently - sql

I have an Exercise table, each Exercise can be 1 of 5 Exercise Type (eg. cardio, timed activity, weights, combination of weights and timed, something else). Each of the different types stores the data in a different manner (eg. cardio is intensity and time, timed is just time in minutes, weights is sets x reps x weight, and something else could be something else).
So its a given that I have an Exercise table, but not sure how to model the Exercise Type and store the associated exercise data for each exercise type. Each Exercise will be of only one Exercise Type and each Exercise Type can belong to many Exercises.
I was leaning towards just an Exercise table and an Exercise Type table and have a many to one relationship, but I can't figure out how best to store each exercises data.
This is going to be modeled for Entity Framework 6 and MS SQL Server.

I think your scenario is good for Inheritance (using Table-per-Hierarchy), here is my suggested design:
public Exercise
{
public int ExerciseId {get;set;}
[ForeignKey("ExerciseBaseTypeId")]
public ExerciseBaseType ExerciseType {get;set;}
[Required]
public int ExerciseBaseTypeId {get;set;}
}
public ExerciseBaseType
{
public int BaseTypeId{get;set;}
public Link<Exercise> Exercises {get;set;}
//put other base properties that is common to all exercise types
}
public Cardio : ExerciseBaseType {
public string Intensity {get;set;}
public int Time {get;set;}
}
public Timed : ExerciseBaseType {
public int Duration {get;set;}
}
public Weight : ExerciseBaseType {
public int Sets {get;set;}
public int Weight {get;set;}
}
Here is your dbcontext file:
public class ExerciseDbContext : DbContext
{
public ExerciseDbContext()
: base("ExerciseDatabase"){ }
}
public DbSet<Exercise> Exercises { get; set; }
public DbSet<ExerciseBaseType> ExerciseTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Exercise>()
.HasRequired(e => e.ExerciseBaseType)
.WithMany(ebt => ebt.Exercises)
.HasForeignKey(e.ExerciseBaseTypeId);
}
As an example, lets add a Timed Exercise and attach it to the exercise with id #1:
ExerciseDbContext db = new ExerciseDbContext();
var timedExercise = new Timed();
timedExercise.Duration = 60;
//set the other base properties
db.Exercises
.Single(e => e.ExerciseId = 1)
.ExerciseTypes.Add(timedExercise);
db.SaveChanges();
Does this make sense?

Related

Designing a hierarchy of abstract classes and using it in EF Core

I am using .NET Core with Entity Framework Core to build a finance app and I want to know how to make my design better.
I have a 1 to Many relationship between two entities, BankAccount and Transaction. In a way that:
1 Account can have many Transactions
1 Transaction Belongs to 1 Account
However, I want to include bank accounts and transactions coming from different 3P sources. And while this relationship and the main fields are common across different sources, each source has a unique set of properties I want to keep.
To achieve this I decided to define these entities as abstract classes. This way, you can only instantiate concrete versions of these entities, each coming from a particular data source.
public abstract class Transaction : BaseEntity
{
public DataSource Source { get; private set; }
public decimal Amount { get; private set; }
public DateTime Date { get; private set; }
public string Name { get; private set; }
public BankAccount BankAccount { get; private set; }
public Guid BankAccountId { get; private set; }
...
}
public abstract class BankAccount : BaseEntity
{
public DataSource Source { get; private set; }
public string Name { get; private set; }
public Balance Balance { get; private set; }
public IEnumerable<Transaction> Transactions {get; private set;}
...
}
Here is a trimmed down example of the concrete implementations:
public class PlaidTransaction : Transaction
{
public string PlaidId { get; private set; }
private PlaidTransaction() : base() { }
public PlaidTransaction(decimal amount, DateTime date, string name, Guid bankAccountId, string plaidId) : base( amount, date, name, bankAccountId)
{
PlaidId = plaidId;
}
}
public class PlaidBankAccount : BankAccount
{
public string PlaidId { get; private set; }
...
}
I am using .Net Core with Entity Framework Core to persist my data and I managed to store my concrete classes all in the same table (TPH approach)
This works great and now all my entities live under the same table. So I can either query all Transactions or those of a certain type using LINQ's OfType<T> extension.
DbSet<Transaction> entities = _context.Set<Transaction>();
IEnumerable<PlaidTransaction> plaidTransactions = entities.OfType<PlaidTransaction>();
However, when I access my BankAccount field from my concrete Transaction I don't get the concrete instance. So something like this doesn't work.
plaidTransactions.Where((t) => t.BankAccount.PlaidId)
Instead I have to cast it:
plaidTransactions.Where((t) => (t.BankAccount as PlaidBankAccount).PlaidId)
What can I do to avoid casting everywhere? I feel there's a missing piece in my design that would make all my code easier. I was thinking of overriding the getters on my concrete classes but I don't know if I can return a derived class to a base class method. Maybe I should move to generics but 1) I still want to keep the fixed relationship between these entities and 2) how would EF Core handle this?

Entity Framework Many to many saving create existing entity

I have two classes with a Many-to-Many relationship. When I save my context, Entity Framework is not using the existing Ids, it creates new entry in my database.
My classes are the following : Country and CountryGroup (in my database EF creates as expected CountryGroupCountries).
public class Country : EntityBase
{
public Country()
{
CountryGroups = new List<CountryGroup>();
}
public virtual List<CountryGroup> CountryGroups { get; set; }
}
public class CountryGroup : EntityBase
{
public CountryGroup()
{
Countries = new List<Country>();
}
public virtual List<Country> Countries { get; set; }
}
public abstract class EntityBase
{
public EntityBase()
{
DateCreate = DateTime.Now;
DateUpdate = DateTime.Now;
DateDelete = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
[Required]
public virtual String Name { get; set; }
}
I use ASP MVC 4 and Entity Framework 5. When I want to save a CountryGroup, I use Countries that are already in my website. The Ids are the right one.
public virtual void Save(TEntity entity)
{
EntityRepository.Insert(entity);
Context.SaveChanges();
}
I just want EF to save my object and the relation to the countries but not. What solution do I have here ? I Feel like I have a misunderstanding of the way EF manages Many To Many.
After many research I believe that my problem lies on the model binder. It must be only creating object without getting them from the context. I overridded my Save Method to replace each Countries in the CountryGroup entity with a fresh one from the context. It is not optimal but I'm going to studie the model binding and then I will arbitrate between those solutions.

PetaPoco mapping properties within properties

I am new to PetaPoco and initially I was liking it but then hit a wall which I simply dont know how to search for.
I have a object which needs to set a property within one of its properties, ie Job.Min.BaseValue. The source of this data is "min_mb".
So basically my object is not a direct mapping of the source table
public class Usage
{
public Decimal BaseValue {get;set;}
public Decimal BaseScale {get;set;}
public Decimal BaseUnit {get;set;}
}
[PetaPoco.TableName("data")]
[PetaPoco.PrimaryKey("date, client_name")]
[PetaPoco.ExplicitColumns]
public class Job
{
[PetaPoco.Column("date")]
public DateTime Date {get;set;}
[PetaPoco.Column("client_name")]
public String ClientName {get;set;}
public Usage Min {get;set;}
public CommvaultJob() { Min = new Usage() { BaseScale=1024, BaseUnit="MB" }; }
}
I think you're just missing the extra type when you call Fetch or Query. This worked for me :
Calling PetaPoco :
var allData = _db.Fetch<TestJobPoco,Usage>("select * from dataTEST");
return View( allData);
The pocos :
[PetaPoco.ExplicitColumns]
public class Usage
{
public Usage()
{
BaseScale=1024;
BaseUnit="MB";
}
[PetaPoco.Column("base_value")]
public Decimal BaseValue {get;set;}
[PetaPoco.Ignore]
public Decimal BaseScale {get;set;}
[PetaPoco.Ignore]
public string BaseUnit {get;set;}
}
[PetaPoco.TableName("dataTEST")]
[PetaPoco.PrimaryKey("id")]
[PetaPoco.ExplicitColumns]
public class TestJobPoco
{
[PetaPoco.Column("id")]
public int Id {get;set;}
[PetaPoco.Column("date")]
public DateTime Date {get;set;}
[PetaPoco.Column("client_name")]
public String ClientName {get;set;}
public Usage Min {get;set;}
public TestJobPoco()
{
//Min = new Usage() { BaseScale=1024, BaseUnit="MB" };
}
}
My test database has an id, date, client_name and base_value columns. The primary key is id so it's slightly different than yours but this shouldn't change the way the poco mapping happens.
If your objects do not map with the table structure, an ORM can't help much.
You will need to do the mapping manually or made new shadow properties that copy the values of the other fields, but this added complexity will defeat the purpose of an ORM.

Building application with Entity framework dbContext API issues

I am developing a WCF Service application. It is going to be a part of large system. It provides some business logic and is based on Entity framework 4.1. I want to divide application code into 2 tiers (projects in VS, dll's): Service (which contains business logic) and DAL.
I have such database model in my project
ClassModel
classID : int, PK
classIdentity : string
teacherName : string
statisticInfo : int
isRegistered : bool
StudentModel
studentID : int, PK
studentIdentity : string
classID : int, FK
For this I am generating code using dbContext templates and I get:
public partial class ClassModel
{
public ClassModel()
{
this.Student = new HashSet<StudentModel>();
}
public int ClassID { get; set; }
public string ClassIdentity { get; set; }
public string TeacherName { get; set; }
public int StatisticInfo { get; set; }
public bool IsRegistered { get; set; }
public virtual ICollection<TerminalModel> Terminal { get; set; }
}
public partial class StudentModel
{
public int StudentID { get; set; }
public string StudentIdentity { get; set; }
public bool IsRegistered { get; set; }
public virtual ClassModel Class { get; set; }
}
I want to expose only some of this information through the service, so I have different model as a data contract:
[DataContract]
public class Clas{
[DataMember]
public string ClassIdentity {get;set;}
[DataMember]
public string TeacherName {get;set;}
[DataMember]
public string ClassMark {get;set;} //computed from statisticInfo
[DataMember]
public int NumberOfStudents {get;set;} //amount of students in this class
}
And my part of my ServiceContract:
[OperationContract]
public void RegsterClass(Clas clas); //(if given clas does not exists adds it and) sets its isRegistered column to True
[OperationContract]
public Clas GetClass(string classIdentity);
As you can see some fields are not present, others are being computed.
In such case I have some concerns about how should I built application properly. Could you write example code which implements the interface methods using everything I mentioned in the way that you think is proper?
Try using T4 templates
It is possible to use T4 templates to generate the dbContext classes, the data transfer objecs (more on that later), the interface as well as all the two methods you have there for each entity in your model: RegsterClass and GetClass. (this would translate to RegsterStudent, GetStudent, and so on for every entity)
Then you can use AutoMapper on NuGet to map from Clas to ClassModel.
I've implemented something similar. I don't pass any of my dbcontext based entities across the wire. I use Data transfer objects for each entity. So a Toyota entity, has a ToyotaDto that has the data annotations and is used for all the WCF CRUD operations. When "Getting" a toyotaDto, I map Toyota to ToyotaDto and return the Dto, when saving, I map the Dto to an entity, of course deleting is done by key, so no Dto necessary.
There are several(1) good(2) examples(3) online you can modify to suit, and if you want I can paste in some of the templates I'm using.

EF4 Code Only - Map Columns to Property Complex type

I have a table like this:
Name
Tree
Iron
Clay
Added
I want to map it to a model like this:
Name
Resources
Tree
Iron
Clay
Added
In makes sense to map it like this, when working with it in my program, but doing it that way in the databse would just make it more complex ... not would not add any useful things.
Is it possible with EF4 Code ONly?
public class Sample
{
public int Id { get; set;} // primary key required
public string Name {get;set;}
public DateTime Added{get;set;}
}
public class Resource
{
// no Id defined here
public string Tree{get;set;}
public string Iron { get;set;}
public string Clay { get;set;}
}
public class SampleDB : DbContext
{
//public DbSet<Resource> Resources { get; set; } // should not be there
public DbSet<Sample> Samples { get; set; }
}