I have a Company class which have a collection of Address.
Here's my Address class:(written top of my head):
public class Address
{
public string Civic;
public string Street;
public City City;
}
This is the City class:
public class City
{
public int Id;
public string Name;
public string SearchableName{ get { //code } }
}
Address is persisted in his own table and have a reference to the city's ID. City are also persisted in is own table.
The City's SearchableName is used to prevent some mistakes in the city the user type. For example, if the city name is "Montréal", the searchable name will be "montreal". If the city name is "St. John", the searchable name will be "stjohn", etc.
It's used mainly to to search and to prevent having multiple cities with a typo in it.
When I save an address, I want an listener/event to check if the city is already in the database. If so, cancel the insert and replace the user's city with the database one. I would like the same behavior with updates.
I tried this:
public bool OnPreInsert(PreInsertEvent @event)
{
City entity = (@event.Entity as City);
if (entity != null)
{
if (entity.Id == 0)
{
var city = (from c in @event.Session.Linq<City>()
where c.SearchableName == entity.SearchableName
select c).SingleOrDefault();
if (city != null)
{
//don't know what to do here
return true;
}
}
}
return false;
}
But if there's already a City in the database, I don't know what to do. @event.Entity is readonly, if I set @event.Entity.Id, I get an "null identifier" exception. I tried to trap insert/update on Address and on Company, but the City if the first one to get inserted (it's logic...)
Any thoughts开发者_如何学Go?
Thanks
You are dealing with this at the wrong level.
This should not happen in an event listener, but in a much higher level (call it service, model, whatever).
Before trying to insert a new record, the service should try to load a City by SearchableName, creating/updating it as needed.
I decided to use a Stored Proc to handle Inserts and updates for this class.
The the SP, if the searchable name already exists, returns it`s id. Else, insert.
It works fine!
精彩评论