I want to make a generic function which would do something similar but I am confused how will it handle the Primary keys (ApplicationId, ClientId, GrainStorageLocationId and LandId) as they are part of different models(LegalNames, GrainStorage and Lands).
public async Task Update(Application oldApplication, Application updatedApplication)
{
_context.Entry(oldApplication).CurrentValues.SetValues(updatedApplication);
// Delete old legal names
foreach (var oldLegalName in oldApplication.LegalNames)
{
if (!updatedApplication.LegalNames.Any(l =>
l.ApplicationId == oldLegalName.ApplicationId &&
l.ClientId == oldLegalName.ClientId))
{
_context.LegalNames.Remove(oldLegalName);
}
}
// Delete old grain storage locations
foreach (var oldGsl in oldApplication.GrainStorageLocations)
{
if (updatedApplication.GrainStorageLocations != null &&
updatedApplication.GrainStorageLocations.All(g =>
g.GrainStorageLocationId != oldGsl.GrainStorageLocationId))
{
_context.GrainStorageLocations.Remove(oldGsl);
}
}
// Delete old Lands
foreach (var oldGsl in oldApplication.Lands)
{
if (updatedApplication.Lands != null &&
updatedApplication.Lands.All(g =>
g.LandId != oldGsl.LandId))
{
_context.Lands.Remove(oldGsl);
}
}
_context.SaveChangesAsync();
}
I want to avoid repetition of code. I tried reflection but doesnt seem to be working as Primary keys are kind of causing problem.
foreach (var variable in oldApplication.LegalNames)
{
var type = typeof(LegalNames);
var propertie = type.GetProperties();
foreach (var property in propertie)
{
var attributes = property.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (attribute.GetType() == typeof(KeyAttribute))
{
string msg = "The Primary Key for the {0} class is the {1} property";
Console.WriteLine(msg, type.Name, property.Name);
}
}
It is not recognizing the primary key at all.
I do have the following code which at least shows that Application Model has ApplicationId as Primary key.
var type = typeof(Application);
var propertie = type.GetProperties();
foreach (var property in propertie)
{
var attributes = property.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (attribute.GetType() == typeof(KeyAttribute))
{
string msg = "The Primary Key for the {0} class is the {1} property";
Console.WriteLine(msg, type.Name, property.Name);
}
}
}
Is there any way to tackle this other than this. Or any way to handle the primary keys?
Thanks.
Aucun commentaire:
Enregistrer un commentaire