Converted List That Got From Reflection - list

I get a list using reflection and I want to fill that list with data this way :
public class SearchCriteria
{
public int SearchValue { get; set; }
public string SearchField { get; set; }
}
public class intListRequest
{
public List<SearchCriteria> SearchList { get; set; }
}
private static void ApplySearchList(intListRequest request)
{
Type type = typeof(intListRequest);
var propers = type.GetProperties();
var propsResult = propers.Where(a => a.Name == "intList");
var prop = propsResult.FirstOrDefault();
if (prop.PropertyType == typeof(List<int>))
{
List<int> newprop = prop.CastTo<List<int>>(); //**error here**//
newprop.Add(SearchValue1);
newprop.Add(SearchValue2);
newprop.Add(SearchValue3);
}
}
my problem Is with the line that I showed, how can I convert that to an int List?

Related

How to access a list inside a class and return as a list of items in asp.netcore?

I have a class showbookings with salesinformation list.
public class ShowBookings
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string ShowId { get; set; }
public DateTime ShowTime { get; set; }
public List<SalesInformation> SalesInformation { get; set; }
}
public class SalesInformation
{
public string SeatNo { get; set; }
public string SalesOrderConfirmationId { get; set; }
}
While calling update method I need to update for SeatNo and SalesOrderConfirmationId but this list is not accessible to me inside for loop.I need to return the list of items after updating showid,seatno SalesOrderConfirmationId but item.SalesInformation = salesInfo shows an error cannot convert salesinformation to generic list.Pls let me know how to sort this issue
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var showBookings = new List<ShowBookings>();
var salesInformation = new List<SalesInformation>();
showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
var _sbList = showBookings.ToList();
foreach (var item in _sbList)
{
var salesInfo = new SalesInformation();
item.ShowId = ShowId;
salesInfo.SeatNo = SeatNo;
item.SalesInformation = salesInfo;
_sbList.Add(item);
}
return _sbList;
}
else
{
return new List<ShowBookings>();
}
}
"SalesInformation" is a list, while salesInfo is a object. You need to do:
item.SalesInformation.Add(salesInfo);
Also, in ShowBooking, inside constructor, initialize your List, else you will receive NullReferenceException.
Try to use
item.SalesInformation = new List<SalesInformation> { salesInfo };
SalesInformation of ShowBookings is List<SalesInformation> type,so you need to set its value with a list.
you already have list of showbookings
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var salesInformation = new List<SalesInformation>();
var showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
return showBookings;
}
else
{
return new List<ShowBookings>();
}
}

wpf DataGrid set itemsource List<object>

I have a problem with DataGrid in wpf
this is a class :
class Superviser
{
public long Id = 0;
public string name = "";
public string father = "";
public string code = "";
}
and this is a function that build a list of this class object
public List<Superviser> allSuperviser()
{
return db.tbPersons.Where(i => i.level == StaticsObject.isSuperviser).Select(x => new Superviser
{
Id = x.Id,
name = x.firstName,
father = x.father,
code = x.code,
}).ToList();
}
and I use this code to set this list in datagrid
dgvPerson.ItemsSource = classPerson.allSuperviser();
but when run program datagrid is empty !
tip : The list is not empty.
Where is the problem?
How do I display this list on DataGrid?
hello agian i solved it
I changed class to :
class Superviser
{
public long Id { get; set; }
public string name { get; set; }
public string father { get; set; }
public string code { get; set; }
public Superviser() { }
public Superviser(long Id, string name, string father, string code)
{
this.Id = Id;
this.name = name;
this.father = father;
this.code = code;
}
}
and change function to :
public List<Superviser> allSuperviser()
{
return db.tbPersons.Where(i => i.level == StaticsObject.isSuperviser).Select(x => new Superviser { Id = x.Id, name = x.firstName + " " + x.lastName, father = x.father, code = x.code }).ToList();
}
And the problem was fixed :)

Iterating through SharePoint 2013 REST API List Items

I am writing a Provider Hosted APP using SP 2013 and I have a data layer which uses REST to CRUD on sharepoint lists. Now I got the List items in JSON format but I am not able to iterate through the list data can you please help in doing that? (is there any class for List Items which I can deserialize into?)
This is the code
public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle)
{
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Credentials = new SharePointOnlineCredentials(userName, password);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
var endpointUri = new Uri(new Uri(webUrl), string.Format("/sites/DTF/_api/web/lists/getbytitle('{0}')/Items", listTitle));
var result = client.DownloadString(endpointUri);
var t = JToken.Parse(result);
return t["d"];
}
}
You need to use the DataContractJsonSerializer class to deserialize the data as is demonstrated here:
http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
To make this work though you have to create classes that match the structure of the Json. The easiest way to do this copying a raw Json response into a tool which will generate the classes like this one:
http://json2csharp.com/
The actual classes you will need to generate varies based on the structure of the data you are getting in your REST response. Here is an example I created that demonstrates making a request, parsing the Json Response and downloading a file based on the result:
public class JsonHelper
{
/// JSON Serialization
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// JSON Deserialization
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
//Custom Json Classes
public class RootObject
{
public D d { get; set; }
}
public class D
{
public GetContextWebInformation GetContextWebInformation { get; set; }
public List<Result> results { get; set; }
}
public class GetContextWebInformation
{
public int FormDigestTimeoutSeconds { get; set; }
public string FormDigestValue { get; set; }
public string LibraryVersion { get; set; }
public string SiteFullUrl { get; set; }
public string WebFullUrl { get; set; }
}
public class Result
{
public ContentType ContentType { get; set; }
public string EncodedAbsUrl { get; set; }
public string FileLeafRef { get; set; }
public Folder Folder { get; set; }
public int FileSystemObjectType { get; set; }
public int Id { get; set; }
public string ContentTypeId { get; set; }
public string Title { get; set; }
public int? ImageWidth { get; set; }
public int? ImageHeight { get; set; }
public string ImageCreateDate { get; set; }
public object Description { get; set; }
public object Keywords { get; set; }
public string OData__dlc_DocId { get; set; }
public int ID { get; set; }
public string Created { get; set; }
public int AuthorId { get; set; }
public string Modified { get; set; }
public int EditorId { get; set; }
public object OData__CopySource { get; set; }
public int? CheckoutUserId { get; set; }
public string OData__UIVersionString { get; set; }
public string GUID { get; set; }
}
//SharePoint Calls
class Program
{
static void Main()
{
string url = "https://sharepoint.wilsonconst.com/";
string filename = "2010-07-23 13.32.22.jpg";
string digest = "";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
digest = sp.d.GetContextWebInformation.FormDigestValue;
}
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
string uri = "_api/web/lists/GetByTitle('Wilson Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
HttpResponseMessage response2 = client.GetAsync(uri).Result;
response2.EnsureSuccessStatusCode();
if (response2.IsSuccessStatusCode)
{
string listItems = response2.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
foreach (Result result in sp.d.results)
{
MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
using(FileStream fileStream = System.IO.File.Create(#"C:\" + result.FileLeafRef))
{
stream.WriteTo(fileStream);
}
}
}
else
{
var content = response.Content.ReadAsStringAsync();
}
}
This seems like a lot of complexity, but really it makes working with Json objects quite easy and takes only moments to setup before you can start calling your custom objects to easily manipulate the data.
Assuming that you want to retrieve data from SharePoint Online the following example demonstrates how to consume SharePoint REST Interface via WebClient Class:
using (var client = new SPRestClient(webUri.ToString()))
{
client.Credentials = GetCredentials(webUri,userName,password);
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
var data = client.GetJson("/_api/lists/getbytitle('Tasks')/items"); //get list items
//print list item's title
foreach (var item in data["d"]["results"])
{
Console.WriteLine(item["Title"]);
}
}
where
public static SharePointOnlineCredentials GetCredentials(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new SharePointOnlineCredentials(userName, securePassword);
}
and
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SharePoint.Client
{
public class SPRestClient : WebClient
{
public SPRestClient(string webUri)
{
BaseAddress = webUri;
FormatType = JsonFormatType.Verbose;
}
public JObject GetJson(string requestUri)
{
return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
}
public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> headers, T data)
{
string result;
var uri = BaseAddress + requestUri;
if (headers != null)
{
foreach (var key in headers.Keys)
{
Headers.Add(key, headers[key]);
}
}
EnsureRequest(method);
switch (method.Method)
{
case "GET":
result = DownloadString(uri);
break;
case "POST":
if (data != null)
{
var payload = JsonConvert.SerializeObject(data);
result = UploadString(uri, method.Method, payload);
}
else
{
result = UploadString(uri, method.Method);
}
break;
default:
throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
}
return JObject.Parse(result);
}
private void EnsureRequest(HttpMethod method)
{
var mapping = new Dictionary<JsonFormatType, string>();
mapping[JsonFormatType.Verbose] = "application/json;odata=verbose";
mapping[JsonFormatType.MinimalMetadata] = "application/json; odata=minimalmetadata";
mapping[JsonFormatType.NoMetadata] = "application/json; odata=nometadata";
Headers.Add(HttpRequestHeader.ContentType, mapping[FormatType]);
Headers.Add(HttpRequestHeader.Accept, mapping[FormatType]);
if (method == HttpMethod.Post)
{
Headers.Add("X-RequestDigest", RequestFormDigest());
}
}
private string RequestFormDigest()
{
var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
var result = UploadString(endpointUrl, "Post");
var contentJson = JObject.Parse(result);
return contentJson["FormDigestValue"].ToString();
}
public JsonFormatType FormatType { get; set; }
}
public enum JsonFormatType
{
Verbose,
MinimalMetadata,
NoMetadata
}
}
SPRestClient.cs

Saving my list to Isolated Storage

I'm having an issue while saving my list items to isolated storage.(Windows Phone 7)
Here is how I defined my list class; I'm using data binding
public class CTransaction
{
public String Date1 { get; set; }
public String Amount1 { get; set; }
public String Type1 { get; set; }
public String Time1 { get; set; }
public String Dis1 { get; set; }
public String Def1 { get; set; }
public CTransaction(String date1, String amount1, String type1, String time1, String dis1, String def1)
{
this.Date1 = date1;
this.Amount1 = amount1;
this.Time1 = time1;
this.Dis1 = dis1;
this.Def1 = def1;
switch (type1)
{
case "FR":
this.Type1 = "Images/a.png";
break;
case "TA":
this.Type1 = "Images/b.png";
break;
case "DA":
this.Type1 = "Images/c.png";
break;
case "CC":
this.Type1 = "Images/mount.png";
break;
}
}
}
Here is how I insert the items to my list; I'm assigning something to the fields and then I'm inserting this into my list like;
List<CTransaction> ctransactionList = new List<CTransaction>();
//some list item filling operations here***
ctransactionList.Insert(0, new CTransaction(DefaultDate, DefaultAmount, RandomType, Times, Dist, Defin));//This one inserts at the top of my list
CTransactionList.ItemsSource = null;
CTransactionList.ItemsSource = ctransactionList; //These two operations refreshes my list
!!Yes, you see how I insert and create my list. Everything is OK. now I want to save ctransactionList
Here is How I save it;(by clicking a button)
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
store.DeleteFile("saver");
}
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Write, store))
{
var serializer = new XmlSerializer(typeof(List<CTransaction>));
serializer.Serialize(stream, ctransactionList);
}
Here is How I load it (By clicking another button)
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Read, store))
{
var reader = new StreamReader(stream);
if (!reader.EndOfStream)
{
var serializer = new XmlSerializer(typeof(List<CTransaction>));
ctransactionList = (List<CTransaction>)serializer.Deserialize(reader);
}
}
}
While debugging, saving operation seems consistent and not raising any error, but while loading; this is the raised error at this line;
ctransactionList = (List<CTransaction>)serializer.Deserialize(reader);
ERROR: There is an error in XML document (3, 4).
If you can help me, I'd really appreciate it.
Thanks in advance
Try this to make your class serializable:
[DataContract]
public class CTransaction
{
[DataMember]
public String Date1 { get; set; }
[DataMember]
public String Amount1 { get; set; }
[DataMember]
public String Type1 { get; set; }
[DataMember]
public String Time1 { get; set; }
[DataMember]
public String Dis1 { get; set; }
[DataMember]
public String Def1 { get; set; }
public CTransaction(String date1, String amount1, String type1, String time1, String dis1, String def1)
{
//your code
}
}
then change the load and save methods to:
public List<CTransaction> LoadFromIsolatedStorage()
{
List<CTransaction> ret = new List<CTransaction>();
try
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Read, store))
{
if (stream.Length > 0)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<CTransaction>));
ret = dcs.ReadObject(stream) as List<CTransaction>;
}
}
}
}
catch (Exception ex)
{
// handle exception
}
}
public void SaveToIsolatedStorage(List<CTransaction> listToSave)
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
store.DeleteFile("saver");
}
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Write, store))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<CTransaction>));
dcs.WriteObject(stream, ctransactionList);
}
}

Entity Framework 5 + Ninject: AutoDetectChanges issue with foreign keys

I'm trying to use the Onion Pattern with Generic Repositories + Unit of work + Entity Framework 5 + Ninject with Asp.net MVC4 but I'm having a problem with EF "DetectChanges" feature and I don't understand why I need to set it to "false".
Could you please help me?
My solution is to add the following line to the constructor of FindingBugContext.cs file:
Configuration.AutoDetectChangesEnabled = false;
In the commented lines of the following code, I'll explain more clearly my isssue.
It's a very simple (and maybe stupid) code reproducing the issue I don't understand and I didn't include the code for all interfaces because I think it's pretty simple to figure it out.
This is my service class, "RobotService.cs":
public class RobotService : IRobotService
{
private readonly IRepository<Body> _repoBody;
private readonly IRepository<BodyPart> _repoBodyPart;
private readonly IRepository<Robot> _repoRobot;
private readonly IUnitOfWork _unitOfWork;
public RobotService(
IRepository<Body> repoBody,
IRepository<BodyPart> repoBodyPart,
IRepository<Robot> repoRobot,
IUnitOfWork unitOfWork)
{
_repoBody = repoBody;
_repoBodyPart = repoBodyPart;
_repoRobot = repoRobot;
_unitOfWork = unitOfWork;
}
public Robot Get(int id)
{
Robot robot = new Robot();
robot = _repoRobot.Get(id);
if (robot != null)
{
Body body = _repoBody.Get(robot.BodyId);
/* FROM NOW ON:
* robot.BodyId = 0 --> instead of 1: WHY???
* robot.Name = "Robby1"
*/
if (body != null)
{
BodyPart head = new BodyPart();
head = _repoBodyPart.Get(body.HeadId);
body.Head = head;
/* FROM NOW ON:
* body.BodyId = 0 --> instead of 1: WHY???
* body.HeadId = 0 --> instead of 1: WHY???
* body.LeftArmId = 0 --> instead of 2: WHY???
* body.RightArmId = 0 --> instead of 3: WHY???
* body.BodyName = "Body1" --> doesn't change
*/
BodyPart leftArm = new BodyPart();
leftArm = _repoBodyPart.Get(body.LeftArmId);
body.LeftArm = leftArm;
BodyPart rightArm = new BodyPart();
rightArm = _repoBodyPart.Get(body.RightArmId);
body.RightArm = rightArm;
robot.Body = body;
}
}
return robot;
}
This is my custom code inside NinjectWebCommon.cs file after installation through NuGet package "Ninject.MVC3":
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(typeof(IRepository<>)).To(typeof(RepositoryBase<>)).InRequestScope();
kernel.Bind<IDbContextFactory>().To<DbContextFactory>().InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IRobotService>().To<RobotService>();
}
This is my DbContext class "FindingBugContext.cs":
public class FindingBugContext : DbContext
{
public FindingBugContext()
: base("FindingBugContext")
{
//Configuration.AutoDetectChangesEnabled = false; //This is the solution
}
public virtual void Commit()
{
base.SaveChanges();
}
private IDbSet<Robot> _robots;
private IDbSet<Body> _bodies;
private IDbSet<BodyPart> _bodyParts;
public virtual IDbSet<T> DbSet<T>() where T : class
{
return Set<T>();
}
public IDbSet<Robot> Robots
{
get { return _robots ?? (_robots = DbSet<Robot>()); }
}
public IDbSet<Body> Bodies
{
get { return _bodies ?? (_bodies = DbSet<Body>()); }
}
public IDbSet<BodyPart> BodyParts
{
get { return _bodyParts ?? (_bodyParts = DbSet<BodyPart>()); }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new DropCreateFindingBugWithSeedData());
modelBuilder.Configurations.Add(new RobotConfiguration());
modelBuilder.Configurations.Add(new BodyConfiguration());
modelBuilder.Configurations.Add(new BodyPartConfiguration());
}
public class DropCreateFindingBugWithSeedData : DropCreateDatabaseAlways<FindingBugContext>
{
protected override void Seed(FindingBugContext context)
{
BodyPart head = new BodyPart() { Type = PartType.Head, PartName = "Head" };
BodyPart leftArm = new BodyPart() { Type = PartType.LeftArm, PartName = "LeftArm" };
BodyPart rightArm = new BodyPart() { Type = PartType.RightArm, PartName = "RightArm" };
Body body = new Body() { BodyName = "Body1", Head = head, HeadId = 1, LeftArm = leftArm, LeftArmId = 2, RightArm = rightArm, RightArmId = 3 };
Robot robot = new Robot() { Name = "Robby1", BodyId = 1, Body = body };
context.Robots.Add(robot);
}
}
public class RobotConfiguration : EntityTypeConfiguration<Robot>
{
public RobotConfiguration()
{
ToTable("Robots");
HasKey(r => r.RobotId)
.Property(r => r.RobotId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(r => r.Body)
.WithMany()
.HasForeignKey(r => r.BodyId);
}
}
public class BodyConfiguration : EntityTypeConfiguration<Body>
{
public BodyConfiguration()
{
ToTable("Bodies");
HasKey(b => b.BodyId)
.Property(b => b.BodyId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(b => b.Head)
.WithMany()
.HasForeignKey(b => b.HeadId)
.WillCascadeOnDelete(false);
HasRequired(b => b.LeftArm)
.WithMany()
.HasForeignKey(b => b.LeftArmId)
.WillCascadeOnDelete(false);
HasRequired(b => b.RightArm)
.WithMany()
.HasForeignKey(b => b.RightArmId)
.WillCascadeOnDelete(false);
}
}
public class BodyPartConfiguration : EntityTypeConfiguration<BodyPart>
{
public BodyPartConfiguration()
{
ToTable("BodyParts");
HasKey(b => b.BodyPartId)
.Property(b => b.BodyPartId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
These are my Entities:
public class Robot
{
public Robot() { Body = new Body(); }
public int RobotId { get; set; }
public string Name { get; set; }
public int BodyId { get; set; }
public Body Body { get; set; }
}
public class Body
{
public Body()
{
Head = new BodyPart();
LeftArm = new BodyPart();
RightArm = new BodyPart();
}
public int BodyId { get; set; }
public string BodyName { get; set; }
public int HeadId { get; set; }
public BodyPart Head { get; set; }
public int LeftArmId { get; set; }
public BodyPart LeftArm { get; set; }
public int RightArmId { get; set; }
public BodyPart RightArm { get; set; }
}
public class BodyPart
{
public int BodyPartId { get; set; }
public PartType Type { get; set; }
public string PartName { get; set; }
}
public enum PartType
{
Head,
LeftArm,
RightArm
}
This is the Unit of Work code:
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContextFactory _dbContextFactory;
private FindingBugContext _context;
public UnitOfWork(IDbContextFactory dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
protected FindingBugContext FindingBugContext
{
get { return _context ?? (_context = _dbContextFactory.Get()); }
}
public void Commit()
{
FindingBugContext.Commit();
}
}
This is the Generic Repository code:
public class RepositoryBase<T> : IRepository<T> where T : class
{
private FindingBugContext _context;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IDbContextFactory dbContextFactory)
{
DbContextFactory = dbContextFactory;
_dbSet = FindingBugContext.Set<T>();
}
public IDbContextFactory DbContextFactory
{
get;
private set;
}
public FindingBugContext FindingBugContext
{
get { return _context ?? (_context = DbContextFactory.Get()); }
}
//Read
public T Get(int id)
{
return _dbSet.Find(id);
}
}
This is my ContextFactory code:
public class DbContextFactory : Disposable, IDbContextFactory
{
private FindingBugContext _context;
public FindingBugContext Get()
{
if (_context == null)
{
_context = new FindingBugContext();
return _context;
}
else
{
return _context;
}
}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
}
}