如何将派生 Class 添加到存储库
How Can I Add A Derived Class To Repository
我需要一个建议。
我有两个 class,其中一个是派生的 class。
我想在一个方法中插入我的基础和派生 class。我怎样才能做到这一点?
//my entities
public class Form
{
public int FormId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Message { get; set; }
}
public class ReturnForm : Form
{
public int OrderId { get; set; }
}
//my repository
public class FormRepository : IFormRepository:IDisposable
{
private readonly MyContext _db;
public FormRepository(MyContext db)
{
_db = db;
}
//I want to insert here Form or ReturnForm objects.
//What can i do?
public void AddFormMessage(Form form)
{
_db.Forms.Add(form);
}
}
我已经解决了业务层的问题
public void AddFormMessage<T>(FormDto formDto)
{
Form form;
var targetClassType = typeof(T);
if (targetClassType == typeof(Form))
{
form = _mapper.Map<Form>(formDto);
}
else if (targetClassType == typeof(ReturnForm))
{
form = _mapper.Map<ReturnForm>(formDto);
}
else
{
throw new Exception("Unknown form type");
}
_unitOfWork.FormRepository.AddFormMessage(form);
}
我需要一个建议。 我有两个 class,其中一个是派生的 class。 我想在一个方法中插入我的基础和派生 class。我怎样才能做到这一点?
//my entities
public class Form
{
public int FormId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Message { get; set; }
}
public class ReturnForm : Form
{
public int OrderId { get; set; }
}
//my repository
public class FormRepository : IFormRepository:IDisposable
{
private readonly MyContext _db;
public FormRepository(MyContext db)
{
_db = db;
}
//I want to insert here Form or ReturnForm objects.
//What can i do?
public void AddFormMessage(Form form)
{
_db.Forms.Add(form);
}
}
我已经解决了业务层的问题
public void AddFormMessage<T>(FormDto formDto)
{
Form form;
var targetClassType = typeof(T);
if (targetClassType == typeof(Form))
{
form = _mapper.Map<Form>(formDto);
}
else if (targetClassType == typeof(ReturnForm))
{
form = _mapper.Map<ReturnForm>(formDto);
}
else
{
throw new Exception("Unknown form type");
}
_unitOfWork.FormRepository.AddFormMessage(form);
}