Patrick
Patrick

Reputation: 2781

Entity Framework - Fill remaining properties

I have a method that receives a Dto Model and map to a Domain Model:

Method:

public void CreateAd(CreateAdDto adDto) { 

    var adDomain = Mapper.Map<CreateAdDto, Ad>(adDto);
}

Dto Object:

public class CreateAdDto
{
    public int Model_Id { get; set; }
}

The Dto map the Domain Model:

public class Ad
{
    public int Id { get; set; }
    public Model Model { get; set; }
}

And the Model:

public class Model
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }
    public string NameStandard { get; set; }
}

I need to get in the CreateAd method access to the Model.NameStandard value, but when I do the mapping, I only have the Model Id, so how do I get the Model Entity with all the properties including the NameStandard value?

Do I have to make a Call to the Model GetById(Model_Id) to get the Model properties or there is another way like a property in the Attach that can bring all the properties?

Or Should I use the Model in the ViewModel and pass to the Dto and to the Domain with all the properties?

Thanks.

Upvotes: 0

Views: 318

Answers (1)

Slauma
Slauma

Reputation: 177153

Yes, you have to call GetById (probably Find or SingleOrDefault?) or use explicit loading:

context.Ads.Attach(adDomain);
context.Entry(adDomain).Reference(a => a.Model).Load();

(EF >= 4.1/DbContext syntax)

Or pass Model to the view in hidden fields and retrieve them back from the view. This might only be a performance question (I could not tell what is better in performance) or maybe a security question (does NameStandard only contain data the user is allowed to see when he inspects the html markup or the traffic on the wire?).

Edit

Sorry, the explicit loading above is nonsense. It would only make sense if you have Ad.Id available and want to fetch the related Model (if the Ad already exists in the database).

So, only GetById is useful in this case.

Upvotes: 1

Related Questions