is this LINQ save function acceptable? (to have a shared INSERT/UPDATE logic like this?) looking for feedback
I am new to WPF and really struggling with 'the right way' to do things...
public void Save(CompanyContact e开发者_StackOverflowntityToSave)
{
try
{
var saveEntity = (from cc in db.CompanyContacts
where cc.CompanyContactId == entityToSave.CompanyContactId
select cc).SingleOrDefault();
if (saveEntity == null)
{
//INSERT logic
entityToSave.CreatedById = new CompanyPersonRepository().GetCompanyPerson(DataContext.Default.LoginUsername).CompanyPersonId;
entityToSave.ModifiedById = entityToSave.CreatedById;
db.CompanyContacts.InsertOnSubmit(entityToSave);
db.CompanyContacts.Context.SubmitChanges();
}
else
{
//UPDATE logic
saveEntity.ModifiedById = new CompanyPersonRepository().GetCompanyPerson(DataContext.Default.LoginUsername).CompanyPersonId;
saveEntity.CompanyId = entityToSave.Company.CompanyId;
saveEntity.FirstName = entityToSave.FirstName;
saveEntity.LastName = entityToSave.LastName;
saveEntity.CompanyContactTypeId = entityToSave.CompanyContactTypeId;
db.CompanyContacts.Context.SubmitChanges();
}
...
if not can you please provide some comments on why it is not, or provide an example of a better way to write LINQ functions if I am not on the right path??
That would work; you can also store the record in the form as a variable, and if its null, the record doesn't exist, but if it does, an update needs to occur. That way, you can minimize your queries, and you can simply assign form values to one object rather than dealing with two.
Alternatively, if you bind a LINQ object to the form, since it implements INotifyPropertyChanged, any changes are immediately bound to the object if you setup the bindings within the form and assign the object as the datacontext.
HTH.
精彩评论