Создание ViewModel, содержащего свойства родительского класса в ASP.NET MVC

Я пытаюсь понять, как создать ViewModel, содержащую свойства класса в моей модели предметной области, а также свойства родительского класса.

Я хочу иметь ViewModel, содержащую все свойства LoadSession, и описание TradingPartner, но я не уверен, как это все сопоставить в ViewModel. Любая помощь или совет будут очень признательны.

Это мой основной класс, к которому я обращаюсь, с именем LoadSession:

public partial class LoadSession
{
    public LoadSession()
    {
        this.AcceptedTransactions = new HashSet<AcceptedTransaction>();
        this.RejectedTransactions = new HashSet<RejectedTransaction>();
    }

    public int LoadSessionId { get; set; }
    public int Import { get; set; }
    public string FilePath { get; set; }
    public string TradingPartnerBatchId { get; set; }
    public System.DateTime Started { get; set; }
    public int RecordsOnFile { get; set; }
    public int RecordsAfterGroupFilter { get; set; }
    public int RecordsAccepted { get; set; }
    public int RecordsRejected { get; set; }
    public System.DateTime Completed { get; set; }
    public bool Success { get; set; }
    public Nullable<int> Extract { get; set; }

    public virtual ICollection<AcceptedTransaction> AcceptedTransactions { get; set; }
    public virtual Extract Extract1 { get; set; }
    public virtual Import Import1 { get; set; }
    public virtual ICollection<RejectedTransaction> RejectedTransactions { get; set; }
}

Свойство Import является внешним ключом для этого класса Import (Import = ImportId):

public partial class Import
{
    public Import()
    {
        this.GroupPlans = new HashSet<GroupPlan>();
        this.ImportGroups = new HashSet<ImportGroup>();
        this.MatchingGroups = new HashSet<MatchingGroup>();
        this.LoadSessions = new HashSet<LoadSession>();
    }

    public int ImportId { get; set; }
    public string Description { get; set; }
    public int Format { get; set; }
    public int Interface { get; set; }

    public virtual Interface Interface1 { get; set; }
    public virtual Format Format1 { get; set; }
    public virtual ICollection<GroupPlan> GroupPlans { get; set; }
    public virtual ICollection<ImportGroup> ImportGroups { get; set; }
    public virtual ICollection<MatchingGroup> MatchingGroups { get; set; }
    public virtual ICollection<LoadSession> LoadSessions { get; set; }
}

Свойство Interface является внешним ключом для этого класса Interface (Interface = InterfaceId):

public partial class Interface
{
    public Interface()
    {
        this.Extracts1 = new HashSet<Extracts1>();
        this.Imports = new HashSet<Import>();
    }

    public int InterfaceId { get; set; }
    public string Description { get; set; }
    public int TradingPartner { get; set; }

    public virtual ICollection<Extracts1> Extracts1 { get; set; }
    public virtual ICollection<Import> Imports { get; set; }
    public virtual TradingPartner TradingPartner1 { get; set; }
}

А свойство TradingPartner является внешним ключом для этого класса TradingPartner (TradingPartner = TradingPartnerId):

public partial class TradingPartner
{
    public TradingPartner()
    {
        this.Interfaces = new HashSet<Interface>();
    }

    public int TradingPartnerId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Interface> Interfaces { get; set; }
}

person Splendor    schedule 20.05.2013    source источник


Ответы (2)


Ну, это все ваши объекты домена, верно...

Создайте репозиторий, который берет объект вашего домена и преобразует его в модель представления с нужными вам свойствами...

Я не уверен, что вам нужно, но из ваших заявлений вы заявляете, что вам нужны свойства Load session + TradingPartner.Description Итак, создайте что-то вроде этого...

public class LoadSessionTradingPrtNrVM
{
    public LoadSession()
    {
        this.AcceptedTransactions = new HashSet<AcceptedTransaction>();
        this.RejectedTransactions = new HashSet<RejectedTransaction>();
    }

    public int LoadSessionId { get; set; }
    public int Import { get; set; }
    public string FilePath { get; set; }
    public string TradingPartnerBatchId { get; set; }
    public System.DateTime Started { get; set; }
    public int RecordsOnFile { get; set; }
    public int RecordsAfterGroupFilter { get; set; }
    public int RecordsAccepted { get; set; }
    public int RecordsRejected { get; set; }
    public System.DateTime Completed { get; set; }
    public bool Success { get; set; }
    public Nullable<int> Extract { get; set; }
    public string Description { get; set; }

    public virtual ICollection<AcceptedTransaction> AcceptedTransactions { get; set; }
    public virtual Extract Extract1 { get; set; }
    public virtual Import Import1 { get; set; }
    public virtual ICollection<RejectedTransaction> RejectedTransactions { get; set; }
}

Чтобы перейти от моделей домена к моделям представления, вы должны использовать репозиторий или какой-либо другой шаблон, который берет то, что вы получаете из своей базы данных, и преобразует его в то, что вам нужно для ваших представлений.

Это немного сыро, но теория должна состояться...

public class DataRepository {

      LoadSessionTradingPrtNrVM TransformToVM(LoadSession inputA, TradingPartner inputB){
            LoadSessionTradingPrtNrVM newOBJ = new LoadSessioNTradingPrtNrVM();
            newOBJ.LoadSessionId = ipnutA.LoadSessionID;
            newOBJ.Import = inputA.Import
            //Here is the property from your Transform object
            newOBJ.Description = inputB.Description
            //...  Continue to transform one object into the other... 
            //You could add as many members from as many different objects as you want into 
            //Your view model following that pattern. 
      }
}

У меня не было возможности запустить это через компилятор C#, но вы должны получить общее представление. Я уверен, что есть более элегантный шаблон, который может выполнить то же самое. Но это достойное решение с моей головы.

person SoftwareSavant    schedule 20.05.2013

Другой вариант — включить объекты модели предметной области в качестве свойств в модель представления. Например:

// View model.
public class UserViewModel
{
    public AddressModel Address;  // Assuming "AddressModel" is a doman model.
    public string FirstName;
    public string LastName;
}

И в представлении вы можете получить доступ к свойствам как:

@Model.Address.AddressLine1
@Model.Address.City
// etc...

Помощники Html отлично справляются с этим, но если вы вручную называете входные данные в своем представлении, не забудьте настроить эти имена так, чтобы они совпадали.

person David Godwin    schedule 20.05.2013