Поскольку эти классы имеют одинаковые поля, вы можете создать a common class
в качестве базового класса для хранения полей.
В моем примере есть три таблицы (tb1, tb2, tb3) и базовый класс (tbBase
), базовый класс не связан с базой данных:
public class tbBase
{
public int Id { get; set; }
public string Description { get; set; }
public string Hint { get; set; }
}
public class tb1: tbBase
{
}
public class tb2 : tbBase
{
}
public class tb3 : tbBase
{
}
Тогда из представления возьмите tbBase class as the parameter
и передайте его методу post, а также a specific table type parameter
, который необходимо изменить.
<form method="post">
Id:<input id="Id" type="text" name="Id" /><br/>
Description: <input id="Description" type="text" name="Description" /><br/>
Hint: <input id="Hint" type="text" name="Hint" /><br/>
table type:<input id="Text1" type="text" name="type" />
<input id="Button1" type="submit" value="button" />
</form>
В PageModel сохраните пары ключ-значение параметра тип и спецификация таблицы c через Dictionary
:
public async Task OnPost(tbBase table, string type)
{
Dictionary<string, Type> TableTypeDictionary = new Dictionary<string, Type>()
{
{ "tb1", typeof(tb1) },
{ "tb2", typeof(tb2) },
{ "tb3", typeof(tb3) }
};
dynamic obj = Activator.CreateInstance(TableTypeDictionary[type]);
for (int i = 0; i < obj.GetType().GetProperties().Length; i++)
{
obj.GetType().GetProperties()[i].SetValue(obj, table.GetType().GetProperty(obj.GetType().GetProperties()[i].Name).GetValue(table, null), null);
}
var ExistingRecord = _context.Find(TableTypeDictionary[type], obj.Id);
if (ExistingRecord == null)
{
obj.Id = 0;//ID is self growing, no need to customize settings
_context.Add(obj);
}
else
{
ExistingRecord.Description = table.Description;
ExistingRecord.Hint = table.Hint;
_context.Attach(ExistingRecord).State = EntityState.Modified;
}
await _context.SaveChangesAsync();
StatusMessage = "Saved!";
await OnGetAsync();
}