Hi,
I have an entity which has a field named "IsDefault". I want to add a method to this entity named SetDefault to set this flag at true. I can only have one entity with this flag at true in my model.
What is the best way to implement such logic ? Should I have this logic in the entity or in my ViewModel ?
The way I did it I have a problem when I manipulate many entities in memory.
Exemple : I create one entity and call my SetDefault method. Then create another one entity and also call SetDefault on it. At last I call SaveChanges.
I would expect to have only the last entity with the IsDefault to true but both are true because I used a query in my method to find the current entity which has IsDefault=true. Obviously the query doesn't know yet about the entity I created in memory.
In my solution I have a problem, if I create many RefNomenclature in the same time before to do a SaveChanges, the query I use to find the previous default entity is always empty.
here is my code :
public partial class RefNomenclature
{
public static RefNomenclature Create(MyEntitiesManager mgr)
{
var refNomenclature = mgr.CreateEntity<RefNomenclature>();
refNomenclature.EntityAspect.AddToManager();
refNomenclature.IsDefault = false;
return refNomenclature;
}
public void SetParDefaut()
{
if (this.IsDefault) return;
var oldDefault = (EntityAspect.EntityManager as MyEntitiesManager).RefNomenclatures.Where(d => d.IsDefault).FirstOrDefault();
if (oldDefault != null)
oldDefault.IsDefault = false;
this.IsDefault = true;
}
}
}