Status라는 이름으로 특정 개체를 업데이트하는 것과 관련된 OnPost 메서드가 있습니다.
public async Task OnPostStatus()
{
Status ExistingRecord = await _context.Status.FirstOrDefaultAsync(m => m.Id == Status.Id);
if (ExistingRecord == null)
{
_context.Status.Add(Status);
} else
{
ExistingRecord.Description = Status.Description;
ExistingRecord.Hint = Status.Hint;
_context.Attach(ExistingRecord).State = EntityState.Modified;
}
await _context.SaveChangesAsync();
StatusMessage = "Saved!";
await OnGetAsync();
}
하지만 실제로 동일한 속성을 가진 4 개의 다른 객체를 사용하여 동일한 OnPost를 수행합니다. 따라서 다음과 같이 개체 유형을 OnPost에 전달하여보다 동적으로 만들고 싶습니다.
public async Task OnPost(string objectName)
{
var objectName ExistingRecord = await _context.(objectName).FirstOrDefaultAsync(m => m.Id == (objectName).Id);
if (ExistingRecord == null)
{
_context.(objectName).Add((objectName));
} else
{
ExistingRecord.Description = (objectName).Description;
ExistingRecord.Hint = (objectName).Hint;
_context.Attach(ExistingRecord).State = EntityState.Modified;
}
await _context.SaveChangesAsync();
StatusMessage = "Saved!";
await OnGetAsync();
}
나는 구체적인 구문을 모른다!
이러한 클래스에는 정확히 동일한 필드가 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에서 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();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다