writing update function to check before adding data in C# - c#

hi I want to write an update function to check the data in my database and if there was a similar column don't add the filed update that filed
here in the code below, I deserialize JSON file
public class CustomerDeserializer
{
public static List<DtoCustomer> Deserialize()
{
List<DtoCustomer> result =
JsonConvert.DeserializeObject<List<DtoCustomer>>(
File.ReadAllText(#"Information.json"));
return result;
}
}
in this part, I read the data and build it
public static Customer CustomerBuild(DtoCustomer dto)
{
return new Customer()
{
FirstName = dto.FirstName,
LastName = dto.LastName,
Address = dto.Address,
Email = dto.Email,
ComapnyName = dto.CompanyName,
PhoneNumber = dto.Phone
};
and then I process data and save them into database
////update function
public static void Process(Customer customer)
{
using (var context = new PracticeEntities1())
{
context.Customers.Add(customer);
context.SaveChanges();
}
}
I want to write an update function before saving to check the data and update it what should I do?

You may do something like this:
using (var context = new PracticeEntities1())
{
var existingCustomer = context.Customers.FirstOrDefault(c => c.Email == customer.Email);
if (existingCustomer != null) {
existingCustomer.FirstName = customer.FirstName;
existingCustomer.LastName = customer.LastName;
existingCustomer.Address = customer.Address;
existingCustomer.CompanyName = customer.CompanyName;
existingCustomer.Phone = customer.Phone;
}
else
{
context.Customers.Add(customer);
}
context.SaveChanges();
}

Related

EF SaveChanges not saving and not throwing exception

I have a method that creates a new user and then insert a row in the User Permission table, but nothing is happening. Here is my code:
// before: creates user
var permission = new UserPermission()
{
UserId = user.Id,
UserName = user.UserName,
Assets = createUserModel.Assets
};
AccountDb.UserPermissions.Add(permission);
var saveChangesResult = AccountDb.SaveChanges();
if (saveChangesResult == 0) // the result is always 0
{
AppUserManager.Delete(user);
return BadRequest("User permission could not be saved");
}
// then: add user to role and return ok
SaveChanges always returns 0 and doesn't update the database, I've already googled for it and tried the following actions:
// no success
AccountDb.UserPermissions.Attach(permission);
// no success either
AccountDb.Entry(permission).State = EntityState.Added;
And I tried in async method too, but no luck.
Here is my "UserPermission" model:
public class UserPermission
{
public int Id { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string _Assets { get; set; }
[NotMapped]
public List<int> Assets
{
get
{
if (_Assets == null) return null;
return Array.ConvertAll(_Assets.Split(';'), Int32.Parse).ToList();
}
set
{
_Assets = String.Join(";", value.Select(x => x.ToString()).ToArray());
}
}
}
It's curious because this method was working lately, but after some changes in "AccountContext" and some rolebacks, I notice that the method wasn't working anymore.
-- edit --
here is the full create method
[HttpPost]
[Route("create")]
public IHttpActionResult CreateUser(CreateUserBindingModel createUserModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (createUserModel.RoleName is null)
{
return BadRequest("There is no role assigned to user");
}
var user = new UserModel()
{
UserName = createUserModel.UserName,
Email = createUserModel.Email,
FirstName = createUserModel.FirstName,
LastName = createUserModel.LastName
};
var addUserResult = AppUserManager.Create(user, createUserModel.Password);
if (!addUserResult.Succeeded)
{
return GetErrorResult(addUserResult);
}
var permission = new UserPermission()
{
UserId = user.Id,
UserName = user.UserName,
Assets = createUserModel.Assets
};
AccountDb.UserPermissions.Add(permission);
var saveChangesResult = AccountDb.SaveChanges();
if (saveChangesResult == 0)
{
AppUserManager.Delete(user);
return BadRequest("User permission could not be saved");
}
var addRoleResult = AppUserManager.AddToRole(user.Id, createUserModel.RoleName);
if (!addRoleResult.Succeeded)
{
AppUserManager.Delete(user);
return GetErrorResult(addUserResult);
}
return Ok(TheModelFactory.Create(user));
}
-- edit 2 --
I was using an Azure db string and I changed to a local db string, but the problem still is the same, UserPermissions Table does not update and no error is emiting.
You are creating a new user, but you never use the result. Your user.Id is always null (or the respective default).
I don't know why your database fails silently (constraints or foreign keys should throw an exception), but you should fix that first. It will probably result in real records being written.
I found a solution!
For some reason, my local instance of AccountContext was the problem, it gets all UserPermissions but doesn't update. So I created a new instance and tried to add the permission:
using (var db = new AccountContext())
{
db.UserPermissions.Add(permission);
var saveChangesResult = db.SaveChanges();
if (saveChangesResult == 0)
{
AppUserManager.Delete(user);
return BadRequest("User permission could not be saved");
}
}
now it's working well. But I don't know why the local AccountDb is not working now if it was working in the past

How to insert/update master-detail in Entity Framework?

I'm trying to make a master-detail Web Form working with Entity Framework and performing insert and update on the same page. I'm new at EF, so I must be making a lot of mistakes here. Can you help me pointing me what's the best practices to perform insert/update on EF? What am I doing wrong here?
In this code, the "New" mode works well, but the "Edit" mode gets this error: "An entity object cannot be referenced by multiple instances of IEntityChangeTracker".
OrdersEntities ordersEntities = new OrdersEntities();
private Order myOrder
{
get { return (Order)Session["myOrder"]; }
set { Session["myOrder"] = value; }
}
public DataTable dtOrderDetails
{
get { return (DataTable)ViewState["dtOrderDetails"]; }
set { ViewState["dtOrderDetails"] = value; }
}
private string Mode
{
get { return (string)ViewState["mode"]; }
set { ViewState["_modo"] = value; }
}
private void btnSaveOrder_Click(object sender, EventArgs e)
{
if (dtOrderDetails.Rows.Count > 0)
{
using (ordersEntities)
{
using (var contextTransaction = ordersEntities.Database.BeginTransaction())
{
try
{
if (Mode == "New")
{
Order newOrder = new Order();
OrderDetails newOrderDetails;
int maxOrderNumber = ordersEntities.Order.Select(o => o.OrderNumber).DefaultIfEmpty(0).Max();
maxOrderNumber++;
newOrder.OrderNumber = maxOrderNumber;
newOrder.Date = DateTime.ParseExact(txtOrderDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
newOrder.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);
newOrder.Status = 1;
ordersEntities.Orders.Add(newOrder);
foreach (DataRow dt in dtOrderDetails.Rows)
{
newOrderDetails = new OrderDetails();
newOrderDetails.OrderNumer = maxOrderNumber;
newOrderDetails.ProductId = Convert.ToInt32(dt["ProductId"]);
newOrderDetails.Quantity = Convert.ToInt32(dt["Quantity"]);
ordersEntities.OrderDetails.Add(newOrderDetails);
}
ordersEntities.SaveChanges();
contextTransaction.Commit();
myOrder = newOrder;
}
if (Mode == "Edit")
{
Order editedOrder = myOrder;
OrderDetails editedOrderDetails;
editedOrder.Date = DateTime.ParseExact(txtOrderDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
editedOrder.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);
ordersEntities.Order.Attach(editedOrder);
ordersEntities.Entry(editedOrder).State = System.Data.Entity.EntityState.Modified;
editedOrder.OrderDetails.Clear();
foreach (DataRow dt in dtOrderDetails.Rows)
{
editedOrderDetails = new OrderDetails();
editedOrderDetails.OrderNumer = editedOrder.OrderNumber;
editedOrderDetails.ProductId = Convert.ToInt32(dt["ProductId"]);
editedOrderDetails.Quantity = Convert.ToInt32(dt["Quantity"]);
ordersEntities.OrderDetails.Add(editedOrderDetails);
}
ordersEntities.SaveChanges();
contextTransaction.Commit();
}
}
catch (Exception ex)
{
contextTransaction.Rollback();
}
}
}
}
}
Here is how you should approach it.
It would be best if you abstract the DbContext away, with this simple interface:
public interface IDataRepository : IDisposable
{
IDbSet<Order> Orders { get; set; }
void Save();
}
Of course, your implementation of IDataRepository is based on EntityFramework. Note that you will need to have a dataRepositoryConnection connection string in your web.config file:
public class EfDataRepository : DbContext, IDataRepository
{
public EfDataRepository() : base("dataRepositoryConnection")
{
}
public IDbSet<Order> Orders { get; set; }
public void Save()
{
this.SaveChanges();
}
}
In my experience, you also need a 'factory', which gives you a new instance of the data repository. This allows you to be the 'owner' of the instance, and you can safely dispose it. Note that the interaction with the DataContext should be minimal - you do your Unity of Work and get rid of it. Don't reuse! You will see it as an example below.
public class DataRepositoryFactory<T> where T : IDataRepository
{
private Type dataRepositoryImplementationType;
public DataRepositoryFactory(T dataRepositoryImplementation)
{
if (dataRepositoryImplementation == null)
{
throw new ArgumentException("dataRepositoryImplementation");
}
this.dataRepositoryImplementationType = dataRepositoryImplementation.GetType();
}
public T Create()
{
return (T)Activator.CreateInstance(this.dataRepositoryImplementationType);
}
}
In your controller (if it were MVC app), or Page backend (forms), it would be best if you use Microsoft Unity to get an instance of DataRepositoryFactory. For now, a manual construction would suffice too.
IDataRepository dataRepository = new EfDataRepository();
var dataRepositoryFactory = new DataRepositoryFactory<IDataRepository>(dataRepository);
Also, you don't need all this Transaction/Commit stuff you have put. It should be transparent for you. EF supports it implicitly, you don't have to be explicit about it.
// See, now you are the 'owner' of the dataRepository
using (var dataRepository = this.dataRepositoryFactory.Create())
{
if (Mode == "New")
{
Order newOrder = new Order();
// This doesn't make sense. Either generate a random order number (e.g. a Guid), or just use the Order.Id as an order number, although I don't recommend it.
int maxOrderNumber = dataRepository.Orders.Select(o => o.OrderNumber).DefaultIfEmpty(0).Max();
maxOrderNumber++;
newOrder.OrderNumber = maxOrderNumber;
newOrder.Date = DateTime.ParseExact(txtOrderDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
newOrder.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);
newOrder.Status = 1;
dataRepository.Orders.Add(newOrder);
foreach (DataRow dt in dtOrderDetails.Rows)
{
OrderDetails newOrderDetails = new OrderDetails();
newOrderDetails.OrderNumer = maxOrderNumber;
newOrderDetails.ProductId = Convert.ToInt32(dt["ProductId"]);
newOrderDetails.Quantity = Convert.ToInt32(dt["Quantity"]);
newOrder.OrderDetails.Add(newOrderDetails);
}
myOrder = newOrder;
}
if (Mode == "Edit")
{
Order editedOrder = dataRepository.Orders.FirstOrDefault(o => o.Id == myOrder.Id);
editedOrder.Date = DateTime.ParseExact(txtOrderDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
editedOrder.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);
editedOrder.OrderDetails.Clear();
foreach (DataRow dt in dtOrderDetails.Rows)
{
OrderDetails editedOrderDetails = new OrderDetails();
editedOrderDetails.OrderNumer = editedOrder.OrderNumber;
editedOrderDetails.ProductId = Convert.ToInt32(dt["ProductId"]);
editedOrderDetails.Quantity = Convert.ToInt32(dt["Quantity"]);
editedOrder.OrderDetails.Add(editedOrderDetails);
}
}
dataRepository.Save();
}
Also, I am pretty sure you have setup the relation between Order and OrderDetails classes incorrectly, in your EF code-first approach.
This is just wrong:
OrderDetails newOrderDetails = new OrderDetails();
newOrderDetails.OrderNumer = maxOrderNumber;
If you post them here, I can fix them for you.

Comparing two lists and return not matching items results with error

I tried to compare two lists by using the Except method. But when I did, I got an error saying:
Cannot convert from 'Systems.Collections.Generic.List<>' to 'System.Linq.IQueryable<>'
'System.Collections.Generic.List<> does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.GEneric.IEnumerable)' has some invalid arguments
I also experienced this when I tried Intersect. I'm trying to compare Sent list and Result list (code and list shown below) and return items that does not have any match. So when I googled for how to do so, I came across the Except method as well as the Intersect.
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
var sent = new List<Sent>();
sent.Add(new Sent() { Address = linaddr1, Data = lindat1 });
var res = new List<Result>();
res.Add( new Result() { AddressOK = linaddr2, DataOK = lindat2 } );
//linaddr1 and 2, lindat1 and 2 contains the address and data shown in the list below
//taken from another part of the entire program
The lists look like such:
sent res
Address Data Address Data
04004C 55AA55 04004C 55AA55
040004 0720 040004 0720
040037 30
04004A FFFF 04004A FFFF
I only tried using this code:
var diff = sent.Except(res).ToList()
but as I've mentioned, it results with the aforementioned errors above.
EDIT: I edited the list. Sorry for that. It's just only a matter of the res list missing one or two or more items from the original list and then comparing both lists to see which item/s is/are missing from the res list.
Use Any:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var sent = new List<Sent>()
{
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result> () {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Where (s => !res.Any (r => s.Address == r.AddressOK && s.Data == r.DataOK ));
foreach (var item in diff)
{
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
}
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
040004 0720
040037 31
Live Code: https://dotnetfiddle.net/ZVuiPd
The types Sent and Result are distinct types, but sent.Except(res) expects them to be the same. That's your first mistake.
The following is a simple (but incorrect) fix:
var diff =
sent
.Except(res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }))
.ToList();
Even though this compiles, and runs, it doesn't remove the duplicates because your Sent doesn't override GetHashCode and Equals, hence it only compares references and not the actual properties.
You can either implement GetHashCode and Equals, or create an IEqualityComparer<Sent> to get this to work.
An IEqualityComparer<Sent> implementation might look like this:
public class SentEqualityComparer : IEqualityComparer<Sent>
{
public int GetHashCode(Sent sent)
{
return sent.Address.GetHashCode() ^ sent.Data.GetHashCode();
}
public bool Equals(Sent left, Sent right)
{
return (left.Address == right.Address) && (left.Data == right.Data);
}
}
And you would use it like so:
var diff =
sent
.Except(
res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }),
new SentEqualityComparer())
.ToList();
This works as you expect.
The other option, to override GetHashCode and Equals, comes with an additional hurdle. The result of GetHashCode should not ever change throughout the lifetime of the object otherwise you can't use the object in a dictionary or any other data structure that relies on the hash code.
So, to make it work, you need to change Address & Data to be read-only.
Here is an implementation of your Sent class that will work correctly:
public sealed class Sent : IEquatable<Sent>
{
private readonly string _Address;
private readonly string _Data;
public string Address { get { return _Address; } }
public string Data { get { return _Data; } }
public Sent(string Address, string Data)
{
_Address = Address;
_Data = Data;
}
public override bool Equals(object obj)
{
if (obj is Sent)
return Equals((Sent)obj);
return false;
}
public bool Equals(Sent obj)
{
if (obj == null) return false;
if (!EqualityComparer<string>.Default.Equals(_Address, obj._Address)) return false;
if (!EqualityComparer<string>.Default.Equals(_Data, obj._Data)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<string>.Default.GetHashCode(_Address);
hash ^= EqualityComparer<string>.Default.GetHashCode(_Data);
return hash;
}
}
If you are comfortable using an AOP component to automate the manual code of implementing IEquatable, another approach would be is to use Equals.Fody:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var a = new Sent { Address = "04004C", Data = "55AA55" };
var b = new Sent { Address = "04004C", Data = "55AA55" };
Console.WriteLine(a.Equals(b)); // True with use of an AOP, False with no AOP
var sent = new List<Sent>() {
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result>() {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Except(
res.Select(r => new Sent { Address = r.AddressOK, Data = r.DataOK })
);
foreach (var item in diff)
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
True
040004 0720
040037 31
If you'll do map Result to Sent very often, you can further shorten your Linq query code to..
var diff = sent.Except(res.Select(r => (Sent)r));
..by automating the mapping of Result to Sent, use implicit operator:
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
public static implicit operator Sent(Result r)
{
return new Sent { Address = r.AddressOK, Data = r.DataOK };
}
}
#Kurisuchin
Suppose you have 2 list and in both you have ID property based on which you want to compare both list and want to store non matching item in third list.
In this Situation following Linq Query can help out.
var result = List2.Where(p => !List1.Any(p2 => p2.ID == p.ID)).ToList();

Simple update with Entity Framework

I have the following code and I cannot achieve saving the changes.
The parameter of my method is a string containing the RefCode of a product I want to modify in the database, then the query is pulling the BaseProduct that is supposed to be modified.
(I tried to simplify the code and set it in English, so I have probably introduced some syntactic errors, but in my code in debug mode, I get all the info FROM the DB). Is there something wrong with the "select new" in the Linq query ?
public static void UpdateProduct(ViewProduct productToUpdate)
{
using (var context = new my_Entities())
{
var BaseProduct = (from prod in context.Product
where prod.Ref == productToUpdate.BaseProduct.RefPrd
select new ViewBaseProduct
{
RefPrd = prod.Ref,
DescrPrd = prod.DescrPrd,
NormeCe = (bool)prod.NormeCE
}).FirstOrDefault();
if (BaseProduct != null)
{
//BaseProduct.NormeCe = false;
BaseProduct = productToUpdate.BaseProduct;
context.SaveChanges();
}
}
}
But BaseProduct is a ViewBaseProduct object, is ViewBaseProduct a entity class? It seems it is a ViewModel class.
You have to get de Product entity, modify his fields and savechanges. It seems you only apply changes to the ViewModel class.
Try this:
public static void UpdateProduct(ViewProduct productToUpdate)
{
using (var context = new my_Entities())
{
var BaseProduct = (from prod in context.Product
where prod.Ref == productToUpdate.BaseProduct.RefPrd)
.FirstOrDefault();
if (BaseProduct != null)
{
//BaseProduct.NormeCe = false;
BaseProduct.field1 = productToUpdate.BaseProduct.field1;
BaseProduct.field2 = productToUpdate.BaseProduct.field2;
//update the necesary fields
//......
context.SaveChanges();
}
}
}
This won't work that way. You should use the CurrentValues.SetValues() method:
contexte.Entry(BaseProduct).CurrentValues.SetValues(productToUpdate.BaseProduct);
I think you have to Try this
public static void UpdateProduct(ViewProduct productToUpdate)
{
using (var contexte = new my_Entities())
{
var BaseProduct = (from prod in contexte.Product
where prod.Ref == productToUpdate.BaseProduct.RefPrd
select new ViewBaseProduct
{
RefPrd = prod.Ref,
DescrPrd = prod.DescrPrd,
NormeCe = (bool)prod.NormeCE
}).FirstOrDefault();
if (BaseProduct != null)
{
BaseProduct.BaseProduct.RefPrd=productToUpdate.BaseProduct.RefPrd
BaseProduct.BaseProduct.DescrPrd=productToUpdate.BaseProduct.DescrPrd
BaseProduct.BaseProduct.NormeCE==(bool)productToUpdate.BaseProduct.NormeCE
contexte.SaveChanges();
}
}
}

Refactoring WPF code behind

I have a method called get Data which executes my SQL and returns some rows of ContactLists containing Aggregated Labels.At the moment this method is in my code behind and would like to move it to a separate Data Access class. I would appreciate your assistance. Thanks!
Is normal, if i understand your code, you do this operation after ContactList initialization:
contactList.Labels = new ObservableCollection<Label>()
{
new Label() {
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
};
For each ContactList is always added one item, you will do something like this:
contactList.Labels = new ObservableCollection<Label>();
foreach(var item in <yourLabelDataSource>)
contactList.Labels.Add(new Label(...));
The solution is like this:
Dictionary<int, ContactList> myContactDictionary = new Dictionary<int, ContactList>();
using (DB2DataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
int id = Convert.ToInt32(dr["CONTACT_LIST_ID"]);
if (!myContactDictionary.ContainsKey(id))
{
ContactList contactList = new ContactList();
contactList.ContactListID = id;
contactList.ContactListName = dr["CONTACT_LIST_NAME"].ToString();
contactList.Labels = new ObservableCollection<Label>()
{
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
};
myContactDictionary.Add(id, contactList);
}
else
{
//Add new label because CONTACT_LIST_ID Exists
ContactList contactList = myContactDictionary[id];
contactList.Labels.Add(
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
);
}
}
}
Ben, for your last question you can use this solution:
else
{
//Add new label because CONTACT_LIST_ID Exists
ContactList contactList = myContactDictionary[id];
string name = dr["LABEL_NAME"].ToString();
var label = contactList.Labels.Where(l => l.Name == name).FirstOrDefault();
if( label != null )
label.Count += Convert.ToInt32(dr["LABEL_COUNT"]);
else
{
contactList.Labels.Add(
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
);
}
I hope this code is readable and helpfulL!
}
This is other response:
Create and Object Model that can contain your required data:
public class DataResult
{
public ObservableCollection<AggregatedLabel> AggregatedLabels { get; set; }
public ObservableCollection<ContactList> ContactLists { get; set; }
}
You can build a method that return DataResult object, in your method (GetData()), you can valorize the two different properties (AggregatedLabels and ContactsList) with your DB Result. In the and you can return DataResult Object.
A little example here:
public DataResult GetData()
{
DataResult result = new DataResult();
result.AggregatedLabels = new ObservableCollection<AggregatedLabel>();
result.ContactLists = new ObservableCollection<ContactList>();
// Manipulate data result with your method logic like in this examle:
foreach(var something in dbResult)
{
ContactList cl = new ContactList() {
//Binding from something
}
result.ContactLists.Add(cl);
}
return result; //return your Object Model with required Data!
}
I hope it is conceptually clear

Categories