Frage

I have two entities: Person and Quote (in one to many relationship)

Person:

 public class Person
 {
    public int PersonID { get; set; }

    [Required]
    [StringLength(20]
    public string Name { get; set; }

    [StringLength(30]
    public string Relation { get; set; }

    public byte[] Image { get; set; }

    [StringLength(50)]
    public string ImageMimeType { get; set; }

    public virtual ICollection<Quote> Quotes { get; set; }
}

Quote:

public class Quote
{
    public int QuoteID { get; set; }

    public int PersonID { get; set; }

    [Required]
    [StringLength(200)]
    public string QuoteName { get; set; }

    [StringLength(400)]
    public string Context { get; set; }

    public DateTime? Date { get; set; }

    public virtual Person Person { get; set; }
}

I want to make a ViewModel for displaying quotes in short format - I need just a few properties - Person Name, QuoteName and Person Image. I could do something casual like they're showing in every ASP.NET MVC tutorial:

 public class QuoteViewModel
 {
    public IEnumerable<Quote> Quotes { get; set; }
 }

Is there a better way rather than creating IEnumerable with type of Quote and loading all properties?

How about creating QuoteShort model and making QuoteViewModel as IEnumerable<QuoteShort> QuotesShort.

In controller I would map every 3 fields from repository to QuoteShort and add it to QuotesShort IEnumerable (even though I don't know how to persist them to QuotesShort IEnumerable )

Some examples appreciated.

War es hilfreich?

Lösung

You can make a QuoteShort ViewModel with just the few properties you need, and then have your view expect IEnumerable<QuoteShort> as its model. You don't necessarily have to wrap that up in another container.

If you have this:

public class QuoteShort{

    public Person Person {get;set;}
    public string Name {get; set;}
    // etc
}

You can do this in the controller:

var quotes = //however you get your list of quotes
var model = (from q in quotes select new QuoteShort
                { Person = q.Person, Name = q.Name /*etc*/ }).ToList();

return View(model);

Andere Tipps

What about something like

public class QuotesShortViewModel
{
    public IEnumerable<QuoteShortViewModel> QuotesShort { get; set; }
}

public class QuoteShortViewModel
{
    // ... the properties you need
}

Create a View that receives a QuotesShortViewModel and iterates through the list, rendering the short quotes as it pleases you.

AutoMapper is useful to map between Models and ViewModels in your controllers.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top