I'm using Entity Framework 6 with database first. See the image for the relevant database schema
I have the following method to save a Set
to the database:
/// <summary>
/// Saves the list of data sources. This assumes that the ModelTemplateID, SetNumber and TaskNumber
/// are already properly set. Adds a new record to the DataSourceGroups table if necessary.
/// </summary>
/// <param name="dataSources">The list of data sources to save</param>
public void SaveSet(IEnumerable<DataSource> dataSources)
{
using (var db = _contextFactory.GetContext())
{
foreach (var dataSource in dataSources)
{
var dataSourceFromDb =
db.DataSources.FirstOrDefault(x => x.DataSourceID == dataSource.DataSourceID);
if (dataSourceFromDb == null)
{ // not in database yet, add it
var dataSourceGroupFromDb =
db.DataSourceGroups.SingleOrDefault(
x => x.ModelTemplateID == dataSource.ModelTemplateID &&
x.SetNumber == dataSource.SetNumber &&
x.TaskNumber == dataSource.TaskNumber);
if (dataSourceGroupFromDb == null)
{ // Add new DataSourceGroup to db
db.DataSourceGroups.Add(new DataSourceGroup
{
ModelTemplateID = dataSource.ModelTemplateID,
SetNumber = dataSource.SetNumber,
TaskNumber = dataSource.TaskNumber
});
}
db.DataSources.Add(dataSource);
}
else
{ // already in database, if any fields are different then update it
if (dataSourceFromDb.QueryID != dataSource.QueryID || // todo make DataSource Comparer
dataSourceFromDb.SourceType != dataSource.SourceType ||
dataSourceFromDb.TargetFormat != dataSource.TargetFormat ||
dataSourceFromDb.SourcePath != dataSource.SourcePath ||
dataSourceFromDb.TargetPath != dataSource.TargetPath)
{
db.DataSources.Attach(dataSource);
db.Entry(dataSource).State = EntityState.Modified;
}
}
}
db.SaveChanges();
}
}
Is this the best way to implement this method? Should I be attaching the DataSources
to the Set
when they are created and then just pass the Set
into the method? Any other critiques welcome.