Auto mapping one to one foreign keys in asp.net boilerplate

1.6k views Asked by At

Suppose I have the following class structure:

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
}

public class PizzaType
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now, I need a DTO class so I can pass to the UI an object for edit, and then pass back to the service for saving to the database. Thus:

[AutoMap(typeof(Pizza))]
public class PizzaEdit
{
    public int Id { get; set; }
    public int PizzaTypeId { get; set; }
}

The goal is to map between Pizza and PizzaEdit as easily as possible so it can be edited in the UI and saved back to the database. Preferably, this will "just work".

What do I need to do to get a mapping from Pizza to PizzaEdit to work and include PizzaTypeId in the DTO object?

pizzaObj.MapTo<PizzaEdit>() works but PizzaTypeId is always null.

I'm open to changing the class structure as needed.

1

There are 1 answers

1
Slava Utesinov On BEST ANSWER

Just add property PizzaTypeId to Pizza class, it will become FK to PizzaType table.

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
    [ForeignKey("PizzaType")]
    public int PizzaTypeId { get; set; }
}

or without FK(NotMapped) via LazyLoading:

public class Pizza
{
    public int Id { get; set; }
    public virtual PizzaType PizzaType { get; set; }
    [NotMapped]
    public int PizzaTypeId { get { return PizzaType.Id; } }
}