Created
February 28, 2018 10:44
-
-
Save SoulFireMage/308c7298989a93d10f7d169be2154f12 to your computer and use it in GitHub Desktop.
Generic Save for our Reverse Poco TT file
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
public interface ICrud //Used to allow the texttemplate in the Model Layer to work. Needs a revisit. | |
{ | |
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.NotifyPropertyChanged(propertyName); | |
return true; | |
} | |
public event PropertyChangedEventHandler PropertyChanged; | |
//protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
protected void NotifyPropertyChanged([CallerMemberName] String propertyName = "") | |
{ | |
if (PropertyChanged == null) return; | |
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
// Only needed if you are using our implementation of static Save/Update from the reverse poco template | |
public class GenericSave<T> where T : class, ICrud | |
{ | |
private static Type _t; | |
public static void Save(List<T> g) | |
{ | |
if (g is null || g.Count < 1) return; | |
if (_t == null) _t = g.First().GetType(); | |
MyDbContext db = new MyDbContext(); | |
foreach (T e in g) | |
{ | |
Update(e, ref db); | |
} | |
} | |
public static T Update(T item) | |
{ | |
if (item == null) return default(T); | |
var itemType = _t != null ? _t : item.GetType(); | |
MyDbContext db = new MyDbContext(); | |
Update(item, ref db); | |
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 MyDbContext db) | |
{ | |
if (item == null || db == null) return default(T); | |
var itemType = _t != null ? _t : item.GetType(); | |
var Table = db.Set(itemType); | |
if (item.Id == 0) | |
{ | |
Table.Add(item); | |
} | |
else | |
{ | |
Table.Attach(item); | |
db.Entry(item).State = System.Data.Entity.EntityState.Modified; | |
} | |
db.SaveChanges(); | |
return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment