How update an entity inside Aggregate

三世轮回 提交于 2019-12-04 20:35:13

First, I think there may be a slight problem with your domain model. It seems to me like 'Campaign' should be an aggregate root entity having a collection of 'Attempt' value objects (or entities). There is no 'Campaigns' aggregate unless you have a parent concept to a campaign which would contain a collection of campaigns. Also, there is no 'Attempts' entity. Instead a collection of 'Attempt' entities or values on the 'Campaign' entity. 'Attempt' may be an entity if it has identity outside of a 'Campaign', otherwise it is a value object. The code could like something like this:

class Campaign {

public string Id { get; set; }

public ICollection<Attempt> Attempts { get; private set; }

public Attempt GetAttempt(string id) {
return this.Attempts.FirstOrDefault(x => x.Number == id);
}

}

class Attempt {
public string Number { get; set; }
public string Attribute1 { get; set; }
}

If you retrieve an Attempt from the Campaign entity and then change some of the properties, you should not have to insert it back into the campaign entity, it is already there. This is how the code would look if you were using NHibernate (similar for other ORMs):

var campaign = this.Session.Get<Campaign>("some-id");

var attempt = campaign.GetAttempt("some-attempt-id");

attempt.Attribute1 = "some new value";

this.Session.Flush(); // will commit changes made to Attempt 

You don't need an Edit method. Your code can modify the Attempts in-place, like so:

Attempt toModify = MyRepository.GetAttemptById(id);
toModify.Counter++;
toModify.Location = "Paris";
MyRepository.SaveChanges(); // to actually persist to the DB

Of course how you name the SaveChanges() is up to you, this is the way Entity Framework names its general Save method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!