Pergunta

I'm building an app using code first and generating the DB.

I can no longer modify the DB so, I can't add/change columns and tables. But the Domain Model (not sure if I'm using the term correctly) requires new properties (that are part of the domain) that can be inferred from the database data, but do not exist explicitly.

My database stores sales info for houses. So I have two tables, Houses and Sales. The tables are related by houseID. Now I want houses to have a property called LastSaleDate, but I can't change the underlying database.

So, How would I properly construct this new property and add it into the appropriate layer? Here is what my poco/entities look like. Just pseudo coded...

[I am trying to learn all I can about the tools and methods I use. I may be completely wrong on all my assumptions and maybe I am to add it to my pocos. If that is the case please explain how that would work]

[Table("HOUSE_TABLE")]
public class house {
 //some properties
public int HouseID {get;set;}
}

[Table("SALE_TABLE")
public class sale {
 //some properties
 public int HouseID {get;set;
 public int SaleID {get;set;}
 public datetime SaleDate {get;set;}
 public virtual House House {get;set;}
}

I almost feel like this would create 2 levels of mapping. Though, I don't believe I've ever seen this done in any code I've seen online.

poco -> AutoMapper?? -> entities -> Automapper -> viewModels
Foi útil?

Solução

This logic most likely belongs on the Entity. Entities should have both data and behaviour. What you seem to be describing is some behaviour that is exposed as a property. So, you should add a property for the derived value to your entity. By default, if the property only has a getter, then EF will not try to map the value to the database.

For example:

[Table("HOUSE_TABLE")]
public class house 
{
    //some properties
    public int HouseID {get;set;}

    public virtual ICollection<Sale> Sales { get; set; }

    public DateTime LastSaleDate 
    {
        get 
        {
            return this.Sales.OrderByDescending(s => s.SaleDate).First();
        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top