Error when changing to ObservableCollection - c#

I am new to WPF and have a beginner question. Whenever I added data to a collection my UI was only getting updated after I restarted the program. I was originally using ICollection but realized I need to use OvservableCollection to update the collection. When I swtiched the Customers property from ICollection to ObservableCollection I get an error on my UpDate method saying I can't implicitly convert. Is possible to cast an ObservableCollection. How else could I fix this issue? Thanks in advance.
ViewModel.cs
public ViewModel()
{
Customers = new ObservableCollection<Customer>();
UpDate();
}
public void UpDate()
{
Customers.Clear();
foreach (var customer in context.Customers.OrderBy(c => c.Name))
{
Customers.Add(customer);
}
}
#region Add new customer,project,program,rev methods
public void AddCustomer(string customerName)
{
using (context = new RevisionModelContainer())
{
var customer = context.Customers;
customer.Add(new Customer { Name = customerName });
context.SaveChanges();
UpDate();
}
}
public ObservableCollection<Customer> Customers { get; set; }
public ObservableCollection<Project> Projects { get; set; }
public ObservableCollection<Program> Programs { get; set; }
public ObservableCollection<Revision> Revisions { get; set; }
public DateTime Dates { get; set; }
public string Notes { get; set; }
Customer.cs
public partial class Customer
{
public Customer()
{
this.Projects = new ObservableCollection<Project>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ObservableCollection<Project> Projects { get; set; }
}

create instance of Customers in ViewModel constructor
public ViewModel()
{
Customers = new ObservableCollection<Customer>();
UpDate();
}
and populate the list when UpDate is called
public void UpDate()
{
Customers.Clear();
foreach(var customer in context.Customers.OrderBy(c => c.Name)) Customers.Add(customer);
}

Related

Computed Properties with Entity Framework and WebApi

How to correctly handle computed properties in EF model?
My try bellow will fail because of "The entity or complex type 'Invoice' cannot be constructed in a LINQ to Entities query."
Consider method "GetInvoice" as WebApi method with allowed querystring.
static void Main(string[] args)
{
var invs = GetInvoice();
invs.FirstOrDefault();
}
public static IQueryable<Invoice> GetInvoice()
{
var model = new Model();
IQueryable<Invoice> inv = model.Invocies.Include(t => t.Items).SelectInvoiceData();
return inv;
}
public static class ExtHelper
{
public static IQueryable<Invoice> SelectInvoiceData(this IQueryable<Invoice> item)
{
return item.Select(c => new Invoice
{
LatestItemName = c.Items.FirstOrDefault().Name
});
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
}
public class Invoice
{
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public string Issuer { get; set; }
[NotMapped]
public string LatestItemName { get; set; }
private ICollection<Item> _items;
public virtual ICollection<Item> Items
{
get { return _items ?? (_items = new Collection<Item>()); }
set { _items = value; }
}
}
EntityFramework 6 does not support creating partial entities like this. Either use anonymous type:
return item.Select(c => new
{
LatestItemName = c.Items.FirstOrDefault().Name
});
Or some DTO class that does not belong to context:
return item.Select(c => new InvoiceDTO
{
LatestItemName = c.Items.FirstOrDefault().Name
});
However in EF Core it is possible to create entities like in your example.

How to use DbRef in LiteDB

How to use DbRef in LiteDB. I have classes for both Customer and Job. I want the Customer to store a list of jobs that the Customer has.
So in the Customer class, I need to have aDbRef<Job> Jobs from what I understand. I have several issues. First, DbRef is not recognized as a type with using LiteDB. Second, I have no idea how to implement it
Job.cs
namespace HMDCompare.Classes
{
public class Job
{
public int id { get; set; }
public string name { get; set; }
}
}
Customer.cs
using LiteDB;
namespace HMDCompare.Classes
{
public class Customer
{
[BsonId]
public int Id { get; set; }
public string Name { get; set; }
public string[] Phones { get; set; }
public bool IsActive { get; set; }
public DbRef<Job> Jobs { get; set; }
}
}
for the DbRef I get in Visual Studio: The type or Namespace name 'DbRef' could not be found.
I am developing in C#/ASP.net 4.5 and with LiteDB 2.0.0-rc
Using LiteDB.2.0.0-rc and following the example in test page, worked fine for me.
public IncludeDatabase() : base("mydb.db")
{
}
public LiteCollection<Folder> Folders { get { return this.GetCollection<Folder>("Folders"); } }
public LiteCollection<SubFolders> SubFolders { get { return this.GetCollection<Media>("SubFolders"); } }
protected override void OnModelCreating(BsonMapper mapper)
{
mapper.Entity<SubFolder>()
.DbRef(x => x.Folder, "Folders");
}
.....
add
var subFolder = new SubFolder()
{
Name = file.Name,
Folder = new Folder { Id = idFolder },
};
using (var db = new IncludeDatabase())
{
db.SubFolders.Insert(subFolder);
}
get
using (var db = new IncludeDatabase())
{
return db.SubFolders
.Include(x => x.Folder)
.FindAll().ToList();
}

already defines member called X c# model

Have class Books and there i should implement two foreign tables. Comments and Rating. This is the class:
public class Books
{
public Books()
{
CommentsList = new List<Comments>();
}
public Books()
{
RatingList = new List<Rating>();
}
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Category { get; set; }
public virtual string ISBN { get; set; }
public virtual string Description { get; set; }
public virtual string Image { get; set; }
// public virtual int CategoryId { get; set; }
public virtual Categories Categories { get; set; }
public virtual IList<Comments> CommentsList { get; set; }
public virtual IList<Rating> RatingList { get; set; }
public virtual void AddComment(Comments comm)
{
comm.Books = this;
CommentsList.Add(comm);
}
public virtual void AddRating(Rating rating)
{
rating.Books = this;
RatingList.Add(rating);
}
}
It gives an error
Error 2 already defines a member called 'Books' with the same
parameter types
How to solve this to have possibility to add comments and rating to a book ?
You have the same constructor two times. I guess you're using Entity Framework and if I recall correctly, you want to change those ILists to ICollections to use the Entity Framework lazy-loading features.
Change
public class Books
{
public Books()
{
CommentsList = new List<Comments>();
}
public Books()
{
RatingList = new List<Rating>();
}
}
To :
public class Books
{
public Books()
{
CommentsList = new List<Comments>();
RatingList = new List<Rating>();
}
}
You simply can't have two constructors that have the same signature. You should consider using a builder pattern instead.
You would typically hide the constructors (make them private) and instead expose static methods like CreateFromComments and CreateFromRatings.
private Books() { }
public static Books CreateFromComments()
{
var ret = new Books();
ret.CommentsList = new List<Comments>();
return ret;
}
public static Books CreateFromRatings()
{
var ret = new Books();
ret.RatingsList = new List<Ratings>();
return ret;
}
may be you can pass a boolean param to set the list to initialize...
public Books(bool comments)
{
if (comments)
CommentsList = new List<Comments>();
else
RatingList = new List<Rating>();
}

Can not seed data with EF Code First

I found the problem, Solution is at comments.
I can create tables and diagram but I can not seed data to table.
1.I installed EF by Nuget.
2.From PM console I wrote Enable-Migrations –EnableAutomaticMigrations.
Model is in All.Model class library and and context methods are in All.Dal class library I did not understand what am I doing wrong can you help me?
This is my context code:
using All.Model;
namespace All.Dal
{
public class AllDb : DbContext
{
public AllDb()
{
Database.Connection.ConnectionString = "Server=SEUPHORIA;Database=AllDb;UID=sa;PWD=123;";
}
public DbSet<Category> Categories { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Line> Lines { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<AllDb>(new DbStrategy());
modelBuilder.Entity<Category>().Property(c => c.Name).IsRequired();
modelBuilder.Entity<Comment>().Property(c => c.Letter).IsRequired();
}
}
}
And this is my strategy code:
using All.Model;
namespace All.Dal
{
public class DbStrategy : DropCreateDatabaseIfModelChanges<AllDb>
{
protected override void Seed(AllDb context)
{
List<Category> CategoryDefault = new List<Category>
{
new Category { Name="Organic", UpID = 0 },
new Category { Name="Object", UpID=0},
new Category { Name="Time",UpID=0},
};
foreach (Category item in CategoryDefault)
{
context.Categories.Add(item);
} context.Users.Add(new User { Name = "sss" });
}
}
}
this is my category class:
public class Category : Standart
{
public int UpID { get; set; }
public string Name { get; set; }
public int LineID { get; set; }
public virtual List<Line> Lines { get; set; }
}
You are adding the items into the DB context but are not committing the changes by calling SaveChanges() on them. Just add this one line:
protected override void Seed(AllDb context)
{
List<Category> CategoryDefault = new List<Category>
{
new Category { Name="Organic", UpID = 0 },
new Category { Name="Object", UpID=0},
new Category { Name="Time",UpID=0},
};
foreach (Category item in CategoryDefault)
{
context.Categories.Add(item);
}
context.Users.Add(new User { Name = "sss" });
context.SaveChanges(); // make sure you save!
}

C# cast to another class with recursion

I am developing a MVC Project with Entity framework and i have a category table like this :
public partial class Categories
{
public Categories()
{
this.Categories1 = new HashSet<Categories>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public Nullable<int> RelatedCategoryId { get; set; }
public virtual ICollection<Categories> Categories1 { get; set; } //Children
public virtual Categories Categories2 { get; set; } //Parent
}
When i get table data with EF, it gives me the object i want. Parents with children.
class Program
{
static Entities db = new Entities();
static void Main(string[] args)
{
List<Categories> categories = db.Categories.Where(item => item.RelatedId == null).ToList();
}
}
With relatedId == null part, i get the main categories which has no parent.
There is no problem this far. But i want to cast categories object which ef returned to another class which is :
public class NewCategories
{
public int Id { get; set; }
public string Name { get; set; }
private List<NewCategories> _subCategories;
public NewCategories()
{
_subCategories= new List<NewCategories>();
}
public List<NewCategories> SubCategories { get { return _subCategories; } }
}
And i want new List<NewCategories> newCategories object.
How can i accomplish that?
Thanks.
I think you have to create a recursive method to convert Categories to NewCategories, something like this (I'm not sure if it works, but it's worth trying):
public NewCategories ConvertToNewCategories(Categories cat){
NewCategories nc = new NewCategories {Id = cat.CategoryId, Name = cat.CategoryName};
nc.SubCategories.AddRange(cat.Categories1.Select(c=>ConvertToNewCategories(c)));
return nc;
}
//Then
List<NewCategories> categories = db.Categories.Where(item => item.RelatedId == null)
.Select(item=>ConvertToNewCategories(item))
.ToList();

Categories