【问题标题】:How Can I Add A Derived Class To Repository如何将派生类添加到存储库
【发布时间】:2021-05-12 15:45:46
【问题描述】:

我需要一个建议。 我有两个类,其中一个是派生类。 我想在一个方法中插入我的基类和派生类。我怎样才能做到这一点?

//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);
    }
}

【问题讨论】:

  • 你能显示你的dbContext吗?

标签: sql-server asp.net-mvc entity-framework design-patterns repository


【解决方案1】:

我已经解决了业务层的问题。

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);
}

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多