Created
January 15, 2018 17:31
-
-
Save SoulFireMage/b314b84b702ff17d2471364afdcca902 to your computer and use it in GitHub Desktop.
Generic Save for use in MVC projects builts with my custom T4 files. EF 6.1+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///Generic Save class for use in the Datalayer where I'm reluctant to couple the Model layer to EF! | |
///Please see the T4 generator for creating files that work with this. | |
namespace DataLayer.Data | |
{ | |
public class GenericSave<T> where T : ICrud | |
{ | |
public static T Update(T item) | |
{ | |
if (item == null) return default(T); | |
var itemType = item.GetType(); | |
using (var db = new ModelEntities()) | |
{ | |
var Table = db.Set(itemType); | |
if (item.ID == 0) | |
{ | |
Table.Add(item); | |
} | |
else | |
{ | |
var entity = Table.Find(item.ID); | |
if (entity == null) | |
{ | |
return item; | |
} | |
db.Entry(entity).CurrentValues.SetValues(item); | |
} | |
db.SaveChanges(); | |
return item; | |
} | |
} | |
/// <summary> | |
/// Added in case I had longer lived contexts where I can rely on the type being part of the context. Would be one round trip. | |
/// </summary> | |
/// <param name="item"></param> | |
/// <param name="db"></param> | |
/// <returns></returns> | |
public static T Update(T item,ref ModelEntities db ) | |
{ | |
if (item == null || db == null) return default(T); | |
var itemType = item.GetType(); | |
using ( db ) | |
{ | |
var Table = db.Set(itemType); | |
if (item.ID == 0) | |
{ | |
Table.Add(item); | |
} | |
else | |
{ | |
db.Entry(item.GetType()).State = System.Data.Entity.EntityState.Modified; | |
} | |
db.SaveChanges(); | |
return item; | |
} | |
} | |
} | |
} | |
Required BaseModel and Inteferface for Generic save and generated files. Implement INotifyproperty changed, however this may be removed in my next version! | |
using System.ComponentModel; | |
using System.Runtime.CompilerServices; | |
namespace DataLayer.Data | |
{ | |
public interface ICrud | |
{ | |
int ID { get; set; } | |
} | |
public abstract class BaseModel : INotifyPropertyChanged | |
{ | |
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) | |
{ | |
if (Equals(storage, value)) | |
{ | |
return false; | |
} | |
// Warning!!! Optional parameters not supported | |
storage = value; | |
this.OnPropertyChanged(propertyName); | |
return true; | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment