Reflexive Association C# - c#

I am trying to implement a reflexive association in C# sharp but couldn't find any example on the web.
I have come up with following
class Employee
{
public string Name { get; set; }
public Employee Boss { get; set; }
public List<Employee> Junoirs;
public Employee (string name)
{
Junoirs = new List<Employee>();
Name = name;
}
static void Main(string[] args)
{
Employee tom = new Employee("Tom");
Employee marry = new Employee("Marry");
Employee jhon = new Employee("Jhon");
Employee foo = new Employee("Foo");
Employee bar = new Employee("Bar");
tom.Junoirs.AddRange(new Employee[] { marry, jhon });
marry.Boss = tom;
jhon.Boss = tom;
marry.Junoirs.AddRange(new Employee[] { foo, bar });
foo.Boss = marry;
bar.Boss = marry;
}
}
Is this a valid example of reflexive association?
How can I automatically add tom as Boss of employees marry and jhon as I add them to list of Junoirs of tom?

You can use methods to add/remove juniors.
If you need add/remove-functionality on the Juniors property, you can implement your own IList or ICollection which handles the book-keeping.
public class Employee
{
public string Name { get; set; }
public Employee Boss
{
get { return _boss; }
set
{
_boss?.RemoveJunior(this);
value?.AddJunior(this);
}
}
public IReadOnlyList<Employee> Juniors => _juniors.AsReadOnly();
private Employee _boss = null;
private readonly List<Employee> _juniors = new List<Employee>();
public Employee(string name)
{
Name = name;
}
public void AddJunior(Employee e)
{
// Remove from existing boss' list of employees
// Can't set Boss property here, that would create infinite loop
e._boss?.RemoveJunior(e);
_juniors.Add(e);
e._boss = this;
}
public void RemoveJunior(Employee e)
{
_juniors.Remove(e);
e._boss = null;
}
}
public class EmployeeTests
{
[Fact]
public void SettingBoss_AddsToEmployee()
{
var b = new Employee("boss");
var e1 = new Employee("1");
e1.Boss = b;
Assert.Same(b, e1.Boss);
Assert.Contains(e1, b.Juniors);
}
[Fact]
public void AddEmployee_SetsBoss()
{
var b = new Employee("boss");
var e1 = new Employee("1");
b.AddJunior(e1);
Assert.Same(b, e1.Boss);
Assert.Contains(e1, b.Juniors);
}
[Fact]
public void NullBoss_RemovesEmployee()
{
var b = new Employee("boss");
var e1 = new Employee("1");
b.AddJunior(e1);
e1.Boss = null;
Assert.Null(e1.Boss);
Assert.DoesNotContain(e1, b.Juniors);
}
[Fact]
public void RemoveEmployee_NullsBoss()
{
var b = new Employee("boss");
var e1 = new Employee("1");
b.AddJunior(e1);
b.RemoveJunior(e1);
Assert.Null(e1.Boss);
Assert.DoesNotContain(e1, b.Juniors);
}
}

Related

Circular Reference in XmlSerializer c#

I'm making an application where I would connect signals with eachother. This creates a circular reference.
The examples I've seen show solutions for a Parent-Child structure. In my application I connect 2 objects from the same class with eachother, so I won't be able to simply ignore one of the references.
I've made a quick example of what my app is doing:
class Program
{
static void Main(string[] args)
{
Info i = new Info();
Employee bs = new Employee("asfdljfoiej", i);
Employee ss = new Employee("asfdljfj", i);
bs.conEm = ss;
ss.conEm = bs;
XmlSerializer xs = new XmlSerializer(typeof(Employee));
const string path = #"C:\Users\Joris.Bosma.KG\source\repos\TestProject\TestProject\bin\Debug\Serializing.xml";
TextWriter txtWriter = new StreamWriter(path);
xs.Serialize(txtWriter, bs);
txtWriter.Close();
//---------------------------------------------------------------------------------------------------------------------------------------
Program p = new Program();
p.Deserialize("Serializing.xml");
}
public void Deserialize(string filename)
{
XmlSerializer xs2 = new XmlSerializer(typeof(Employee));
Employee em;
using (Stream reader = new FileStream(filename, FileMode.Open))
em = (Employee)xs2.Deserialize(reader);
Console.Write(em.name);
}
}
public class Employee
{
public int Id = 1;
public String name = "John Smith";
public string subject = "Physics";
public string random;
public List<Employee> Employees;
public Employee conEm;
public Info inf;
public Employee()
{
}
public Employee(String s, Info i)
{
random = s;
inf = i;
}
}
public class Info : Employee
{
public string add = "Street";
}
The problem lays in
bs.conEm = ss
ss.conEm = bs
Thanks for helping in advance!
If structure of employees is not hierarchial (loops are possible), I would recommend to exclude properties 'conEm' and 'Employees' from serialization and store data in structure like this:
public class Relationship {
public int ParentId { get; set; }
public int ChildId { get; set; }
}
public class DataStore {
// flat list of employees
public List<Employee> Employees { get; set; }
// list of all relationship between Employees
public List<Relationship> Relationships { get; set; }
}
This structure needs to be populated before serialization.
After deserialization, structure can easily be restored:
var index = data.Employees.ToLookup(e => e.Id);
data.Relationships.Iter(r => {
var parent = index[r.ParentId].FirstOrDefault();
var child = index[r.ChildId].FirstOrDefault();
if (parent != nuu && child != null) {
parent.Employees.Add(child);
child.conEm = parent;
}
});

Unit test for update method in C# using Mock

I am trying to write a unit test for My Processor class I have two problems
I do not know how to test my Methods Only.
this is my processor
OrderProcessor class
public class OrderProcessor
{
public void Process(CustomersOrder order)
{
var oldOrder = _repository.GetOldorderId(order.Code.Value);
if (oldOrder != 0)
{
updateOrder(order);
}
else
{
SaveOrder(order);
}
}
private void updateOrder(CustomersOrder order)
{
_repository.UpdateOrder(order);
}
private void SaveOrder(CustomersOrder order)
{
_repository.SaveOrder(order);
}
}
}
Repository class
public class Repository : IRepository
{
private static PracticeEntities4 _context;
public Repository(PracticeEntities4 context)
{
_context = context;
}
public int GetOldCustomerId( int customerCode)
{
var CuID= _context.Customers.First(e => e.Code == customerCode);
return CuID.Id;
}
public int GetOldorderId(int orderCode)
{
var oldOrder = _context.CustomersOrders.FirstOrDefault(e => e.Code == orderCode);
return oldOrder.Id;
}
public void SaveCustomer(Customer customer)
{
_context.Customers.Add(customer);
_context.SaveChanges();
}
public void SaveOrder(CustomersOrder order)
{
_context.CustomersOrders.Add(order);
_context.SaveChanges();
}
public void UpdateOrder(CustomersOrder order)
{
_context.CustomersOrders.AddOrUpdate(order);
_context.SaveChanges();
}
}
and this is My unit test I don't know how to fix it and where is the problem exactly and also I want to test the Methods too.
UnitTests Class
[TestClass]
public class OrderProcessorTest
{
[ClassInitialize]
{...}
[TestInitialize]
public void TestInitialize()
{
....
}
[TestMethod]
public void Customer_OrderProcess()
{
//Arange
Mock<IRepository> mock= new Mock<IRepository>();
//Act
mock.Setup(e => e.GetOldCustomerId(1001)).Returns(3);
mock.Setup(e => e.GetOldStoreId(200)).Returns(3);
var dtos = OrderDeserializer.Deserialize(path);
var dto = dtos.First(e => e.Code == 300);
OrderBuilder builder = new OrderBuilder(mock.Object);
builder.OrderBuild(dto);
//Asset
Assert.AreEqual(0, _orders.Count);
}
}
Order Builder Class
public class OrderBuilder
{
public IRepository _repository { get; set; }
public OrderBuilder(IRepository repository)
{
_repository = repository;
}
public CustomersOrder OrderBuild(OrderDto dto)
{
var oldStoreId = _repository.GetOldStoreId(dto.StoreCode);
var oldCustomerId = _repository.GetOldCustomerId(dto.CustomerCode);
return new CustomersOrder()
{
OrderDate = Convert.ToDateTime(dto.OrderDate),
OrderStatus = dto.OrderStatus,
DeliveryDate = Convert.ToDateTime(dto.DeliveryDate),
CustomerId = oldCustomerId,
StoreId = oldStoreId,
Code = dto.Code
};
}
}
In your code I see that there are all sorts of Mocking and Initial test setups that is taking place without a clear intention on what to test.
Unit Test: What ?
Tests a unit of an application without its external dependencies
Unit Test: Why ?
Makes refactoring faster and ensures you don't break existing portion of your code
Unit Test: Steps ?
We first need to re-factor the code before we do unit tests. Modularity is the key
By using Interfaces remove the tight couplings in the code
Inject the dependency via method parameters, constructor, properties or use Dependency Injection
Consider using Mock objects, as a good practice, only when dealing with external dependency.
In the [TestMethod] we organize the tests into 3 categories Arrange -> Act -> Assert
Example:
//Arrange
var res = new Reservation();
//Act
var op = res.Method(new User{IsAdmin=true});
// Assert
Assert.IsTrue(op);
Naming Conventions in UnitTests:
TestProjectName:     [InserProjectName].UnitTests
TestClasses:         [InsertClassName]Tests
TestMethod:         [MethodYourTesting]_[Scenario]_[ExpectedBehavior]
I have created a Console app as close as possible to your problem
(minus the DBContext) that you can replicate on your PC to understand
the various portions.
All the domain classes are part of one single
file for the sake of testability to reproduce faster.
Console App Project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackOrderProcessor
{
public class CustomersOrder
{
public OrderDto Order { get; set; }
public List<CustomersOrder> CustomersOrders = new List<CustomersOrder>();
public DateTime OrderDate { get; set; }
public string OrderStatus { get; set; }
public int CustomerID { get; set; }
public int Code { get; set; }
public int ID { get; set; }
}
public class Customer
{
public OrderDto Order { get; set; }
public List<Customer> Customers = new List<Customer>();
public int Code { get; set; }
public int ID { get; set; }
}
public class OrderDto
{
public DateTime OrderDate { get; set; }
public int CustomerCode { get; set; }
public string OrderStatus { get; set; }
public int Code { get; set; }
}
public interface IRepository
{
int GetOldCustomerId(int customerCode);
int GetOldOrderId(int orderCode);
void SaveCustomer(Customer customer);
void SaveOrder(CustomersOrder order);
}
public class Repository : IRepository
{
private readonly Customer _cust;
private readonly CustomersOrder _custOrder;
public Repository(Customer cust, CustomersOrder custOrder )
{
_cust = cust;
_custOrder = custOrder;
}
public int GetOldCustomerId(int customerCode)
{
var cuId = _cust.Customers.First(e => e.Code == customerCode);
return cuId.ID;
}
public int GetOldOrderId(int orderCode)
{
var oId = _custOrder.CustomersOrders.FirstOrDefault(e => e.Code == orderCode);
return oId.ID;
}
public void SaveCustomer(Customer customer)
{
_cust.Customers.Add(customer);
}
public void SaveOrder(CustomersOrder order)
{
_custOrder.CustomersOrders.Add(order);
}
}
public class OrderProcess
{
private readonly IRepository _repository;
public OrderProcess(IRepository repository)
{
_repository = repository;
}
public void Process(CustomersOrder order)
{
var oldOrder = _repository.GetOldOrderId(order.Code);
if (oldOrder == 0)
_repository.SaveOrder(order);
}
}
public class OrderBuilder
{
private readonly IRepository _repository;
public OrderBuilder(IRepository repository)
{
_repository = repository;
}
public CustomersOrder OrderBuild(OrderDto dto)
{
var oldCustomerId = _repository.GetOldCustomerId(dto.CustomerCode);
return new CustomersOrder()
{
Order = dto,
OrderDate = Convert.ToDateTime(dto.OrderDate),
OrderStatus = dto.OrderStatus,
ID = oldCustomerId,
CustomerID = oldCustomerId,
Code = dto.Code
};
}
}
class Program
{
static void Main(string[] args)
{
var cust = new Customer();
var custOrder = new CustomersOrder();
#region PopulatingCustomer
//Populating OrderDto
var dto1 = new OrderDto { Code = 1, CustomerCode = 1, OrderDate = DateTime.Now.Date, OrderStatus = "OK" };
//Populating Customer
var customerList = cust.Customers = new List<Customer>();
var customerOrderList = custOrder.CustomersOrders = new List<CustomersOrder>();
var customer1 = new Customer
{
Code = 1,
ID = 1, Order=dto1
};
var customer2 = new Customer
{
Code = 2,
ID = 2,
};
customerList.Add(customer1);
customerList.Add(customer2);
#endregion
#region PopulatingCustomerOrder
var customersOrder1 = new CustomersOrder { Code = 1, CustomerID = 1, ID = 1, Order = dto1, OrderDate = dto1.OrderDate, OrderStatus = dto1.OrderStatus };
customerOrderList.Add(customersOrder1);
#endregion
#region InvokingMethods
//IRepository
IRepository IRepo = new Repository(cust,custOrder);
//OrderProcessor
var orderProcesor = new OrderProcess(IRepo);
//OrderBuilder
var dto2 = new OrderDto { Code = 2, CustomerCode = 2, OrderDate = DateTime.Now.Date, OrderStatus = "OK" };
var oBuilder = new OrderBuilder(IRepo);
var newCustOrder = oBuilder.OrderBuild(dto2);
customerOrderList.Add(newCustOrder);
#endregion
Console.Read();
}
}
}
UnitTest Project
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StackOrderProcessor;
namespace StackOrderProcessor.UnitTests
{
[TestClass]
public class RepositoryTests
{
[TestMethod]
public void GetOldCustomerId_WhenCalled_ReturnsOId()
{
//Arrange
var cust = new Customer();
var custOrder = new CustomersOrder();
IRepository repo = new Repository(cust,custOrder);
var customerList = cust.Customers = new List<Customer>();
var dto1 = new OrderDto { Code = 1, CustomerCode = 1, OrderDate = DateTime.Now.Date, OrderStatus = "OK" };
var customer1 = new Customer
{
Code = 1,
ID = 1,
Order = dto1
};
var customer2 = new Customer
{
Code = 2,
ID = 2,
};
customerList.Add(customer1);
customerList.Add(customer2);
//Act
repo.GetOldCustomerId(1);
//Assert
Assert.AreEqual(1, 1); //Test will Pass as we have a customer of Code 1
}
[TestMethod]
//MethodName_Scenario_Expectedbehavior
public void SaveCustomer_WhenCalled_AddsNewCustomer()
{
var cust = new Customer();
var custOrder = new CustomersOrder();
IRepository repo = new Repository(cust, custOrder);
var customerList = cust.Customers = new List<Customer>();
var dto1 = new OrderDto { Code = 1, CustomerCode = 1, OrderDate = DateTime.Now.Date, OrderStatus = "OK" };
var customer1 = new Customer
{
Code = 1,
ID = 1,
Order = dto1
};
var customer2 = new Customer
{
Code = 2,
ID = 2,
};
customerList.Add(customer1);
customerList.Add(customer2);
//Act
var custToSave = new Customer
{
Code = 3,
ID = 3,
Order = null
};
repo.SaveCustomer(custToSave);
//Assert
Assert.AreEqual(3, customerList.Count);
}
}
[TestClass]
public class OrderProcessor1Tests
{
[TestMethod]
public void Process_WhenOrderIsZero_AddsNewCustomerOrder()
{
//Arrange
var cust = new Customer();
var custOrder = new CustomersOrder();
var customerOrderList = custOrder.CustomersOrders = new List<CustomersOrder>();
IRepository repo = new Repository(cust, custOrder);
var orderProcessor = new OrderProcess(repo);
var dto1 = new OrderDto { Code = 1, CustomerCode = 1, OrderDate = DateTime.Now.Date, OrderStatus = "OK" };
var custOrder1 = new CustomersOrder { ID = 1, Code = 1, CustomerID = 1, Order = dto1, OrderDate = dto1.OrderDate, OrderStatus = dto1.OrderStatus };
customerOrderList.Add(custOrder1);
//Act
orderProcessor.Process(custOrder1);
//Assert
Assert.AreEqual(1, customerOrderList.Count);
}
}
}
Note: Make sure to add reference of StackOrderProcessor in StackOrderProcessor.UnitTests
You will still need to better organize the Unit Test Methods, this was just for demonstration purposes, I hope concepts are much more clear now
Your question doesn't have enough information, you don't need your repository code for this question, but OrderBuiler class and _orders field needs. I'm sorry for this comment in answers location.

How to update an existing item ViewModel in an ObservableCollection which is populated by an Observable

Having an ObservableCollection that populates by an observable, I would like to know what is the most effective and right way to update an item ViewModel in the collection if already exists. I came up with 2 solutions:
Solution 1
Make the MainViewModel responsible to identify if the item already exists in the ObservableCollection, if yes perform an update:
MainViewModel.cs
private readonly SortedObservableCollection<IConversationPreviewViewModel> _conversationPreviews = new SortedObservableCollection<IConversationPreviewViewModel>();
public void SubscribeOnConversations()
{
_observeConversationsUseCase
.Conversations
.ObserveOn(_schedulerProvider.Dispatcher)
.Subscribe(OnNext);
}
private void OnNext(Conversation conversation)
{
var previewViewModel = _conversationPreviews.FirstOrDefault(it => it.ConversationId == conversation.ConversationId);
if (previewViewModel == null)
{
IConversationPreviewViewModel conversationPreview = _conversationPreviewFactory.Create(conversation);
_conversationPreviews.Add(conversationPreview);
}
else
{
previewViewModel.UpdateConversation(conversation);
}
}
Solution 2
The main view model is only responsible to add new items but the updating is the responsibility of each item view model itself, subscribing each one to the observable:
public class Conversation
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ConversationItemViewModel
{
private int Id { get; set; }
public string Text { get; private set; }
public ConversationItemViewModel(Conversation conversation, ObserveConversations observeConversations)
{
Id = conversation.Id;
Text = conversation.Name;
PrintStatus("ctor");
observeConversations.Conversations.Where(it => it.Id == Id).Subscribe(OnNext);
}
private void OnNext(Conversation conversation)
{
Text = conversation.Name;
PrintStatus("OnNext");
}
private void PrintStatus(string from)
{
Console.WriteLine($"Id:{Id} Text:{Text} From: {from}");
}
}
public class ObserveConversations
{
public IConnectableObservable<Conversation> Conversations { get; }
public ObserveConversations()
{
Conversations = ConversationsArriving();
Conversations.Connect();
}
public IConnectableObservable<Conversation> ConversationsArriving()
{
var list = new List<Conversation>() { new Conversation(){Id = 1, Name = "name1"},
new Conversation() {Id = 2, Name = "name2" },
new Conversation() {Id = 3, Name = "name3"},
new Conversation() {Id = 2, Name = "updatedname2"}, // Update this
new Conversation() {Id = 4, Name = "name4"},
new Conversation() {Id = 3, Name = "updatedname3"}, // Update this
};
return list.ToObservable().Delay(TimeSpan.FromSeconds(1)).Publish();
}
}
public class MainViewModel
{
private readonly ObserveConversations _observeConversations;
public MainViewModel(ObserveConversations observeConversations)
{
_observeConversations = observeConversations;
}
private ObservableCollection<ConversationItemViewModel> ConversationItemViewModels { get; } = new ObservableCollection<ConversationItemViewModel>();
public void Start()
{
_observeConversations.Conversations
.Distinct(it => it.Id)
.Subscribe(OnNext);
}
private void OnNext(Conversation conversation)
{
ConversationItemViewModels.Add(new ConversationItemViewModel(conversation, _observeConversations));
}
}
class Program
{
static void Main(string[] args)
{
var observeConversations = new ObserveConversations();
var mainViewModel = new MainViewModel(observeConversations);
mainViewModel.Start();
Console.ReadLine();
}
Personally, I find the solution 2 better since it delegates the responsibility of update to each ViewModel each self.
Is there a more fine-grained solution than those?
Could the creation of multiple subscriptions for each item ViewModel in solution 2 create performance issues?

How to do Cascading Include in LiteDB

here is example on how to store cross-referenced entities in LiteDB. LiteDB stores the cross-referenced entities perfectly fine, but problem comes when I am trying to find/load entities back. My goal is NOT ONLY the requested entity but also referenced ones. There is quick tutorial section "DbRef for cross references" on LiteDB webpage how one can realize it. LiteDB has "Include" option (which is called before "FindAll") which says which referenced entities must be loaded as well. I am trying to achieve it in this code example but with no results, i.e, the code raises Exception("D_Ref") meaning "D_Ref" reference is not loaded:
namespace _01_simple {
using System;
using LiteDB;
public class A {
public int Id { set; get; }
public string Name { set; get; }
public B B_Ref { set; get; }
}
public class B {
public int Id { set; get; }
public string Name { set; get; }
public C C_Ref { set; get; }
}
public class C {
public int Id { set; get; }
public string Name { set; get; }
public D D_Ref { set; get; }
}
public class D {
public int Id { set; get; }
public string Name { set; get; }
}
class Program {
static void Main(string[] args) {
test_01();
}
static string NameInDb<T>() {
var name = typeof(T).Name + "s";
return name;
}
static void test_01() {
if (System.IO.File.Exists(#"MyData.db"))
System.IO.File.Delete(#"MyData.db");
using (var db = new LiteDatabase(#"MyData.db")) {
var As = db.GetCollection<A>(NameInDb<A>());
var Bs = db.GetCollection<B>(NameInDb<B>());
var Cs = db.GetCollection<C>(NameInDb<C>());
var Ds = db.GetCollection<D>(NameInDb<D>());
LiteDB.BsonMapper.Global.Entity<A>().DbRef(x => x.B_Ref, NameInDb<B>());
LiteDB.BsonMapper.Global.Entity<B>().DbRef(x => x.C_Ref, NameInDb<C>());
LiteDB.BsonMapper.Global.Entity<C>().DbRef(x => x.D_Ref, NameInDb<D>());
var d = new D { Name = "I am D." };
var c = new C { Name = "I am C.", D_Ref = d };
var b = new B { Name = "I am B.", C_Ref = c };
var a = new A { Name = "I am A.", B_Ref = b };
Ds.Insert(d);
Cs.Insert(c);
Bs.Insert(b);
As.Insert(a);
}
using (var db = new LiteDatabase(#"MyData.db")) {
var As = db.GetCollection<A>(NameInDb<A>());
var all_a = As
.Include(x => x.B_Ref)
.FindAll();
foreach (var a in all_a) {
if (a.B_Ref == null)
throw new Exception("B_Ref");
if (a.B_Ref.C_Ref == null)
throw new Exception("C_Ref");
if (a.B_Ref.C_Ref.D_Ref == null)
throw new Exception("D_Ref");
}
}
}
}}
after small research I've resolved the issue simply by adding extra "Include" parameterize by "x => x.B_Ref.C_Ref" lambda where x.B_Ref.C_Ref is a path in hierarchy of references:
var all_a = As
.Include(x => x.B_Ref)
.Include(x => x.B_Ref.C_Ref)
.FindAll();
Here is complete example
namespace _01_simple {
using System;
using LiteDB;
public class A {
public int Id { set; get; }
public string Name { set; get; }
public B B_Ref { set; get; }
}
public class B {
public int Id { set; get; }
public string Name { set; get; }
public C C_Ref { set; get; }
}
public class C {
public int Id { set; get; }
public string Name { set; get; }
public D D_Ref { set; get; }
}
public class D {
public int Id { set; get; }
public string Name { set; get; }
}
class Program {
static void Main(string[] args) {
test_01();
}
static string NameInDb<T>() {
var name = typeof(T).Name + "s";
return name;
}
static void test_01() {
if (System.IO.File.Exists(#"MyData.db"))
System.IO.File.Delete(#"MyData.db");
using (var db = new LiteDatabase(#"MyData.db")) {
var As = db.GetCollection<A>(NameInDb<A>());
var Bs = db.GetCollection<B>(NameInDb<B>());
var Cs = db.GetCollection<C>(NameInDb<C>());
var Ds = db.GetCollection<D>(NameInDb<D>());
LiteDB.BsonMapper.Global.Entity<A>().DbRef(x => x.B_Ref, NameInDb<B>());
LiteDB.BsonMapper.Global.Entity<B>().DbRef(x => x.C_Ref, NameInDb<C>());
LiteDB.BsonMapper.Global.Entity<C>().DbRef(x => x.D_Ref, NameInDb<D>());
var d = new D { Name = "I am D." };
var c = new C { Name = "I am C.", D_Ref = d };
var b = new B { Name = "I am B.", C_Ref = c };
var a = new A { Name = "I am A.", B_Ref = b };
Ds.Insert(d);
Cs.Insert(c);
Bs.Insert(b);
As.Insert(a);
}
using (var db = new LiteDatabase(#"MyData.db")) {
var As = db.GetCollection<A>(NameInDb<A>());
var all_a = As
.Include(x => x.B_Ref)
.Include(x => x.B_Ref.C_Ref)
.Include(x => x.B_Ref.C_Ref.D_Ref)
.FindAll();
foreach (var a in all_a) {
if (a.B_Ref == null)
throw new Exception("B_Ref");
if (a.B_Ref.C_Ref == null)
throw new Exception("C_Ref");
if (a.B_Ref.C_Ref.D_Ref == null)
throw new Exception("D_Ref");
}
}
}
}}
I hope it saves someone's time.
Update: LiteDB author says there is no support for Cascading Include. But it is planned in the next version (see issue). Consider, once, let say, B_Ref is a Lite of B, then there is no mechanism to force deeper Include.

Question about Auto-Implemented Properties C#

I have this code:
void Main()
{
List<Employee> employeeList;
employeeList = new List<Employee>
{
{new Employee("000001", "DELA CRUZ, JUAN T.")},
{new Employee("000002", "GOMEZ, MAR B.")},
{new Employee("000003", "RIVERA, ERWIN J.")}
};
employeeList.Dump();
}
public class Employee
{
public string EmployeeNo { get; set; }
public string Name { get; set; }
public Employee(string employeeNo, string name)
{
this.EmployeeNo = employeeNo;
this.Name = name;
}
}
How should I make a new instance of Employee class using the properties only and add that instance to the employeeList (I mean not using the class constructor of employee)?
I already made a solution but it's too lengthy. How should I shorten it?
void Main()
{
List<Employee> employeeList;
#region - I want to shorten these lengthy codes.
Employee employee1 = new Employee();
employee1.EmployeeNo = "000001";
employee1.Name = "DELA CRUZ, JUAN T.";
Employee employee2 = new Employee();
employee2.EmployeeNo = "000002";
employee2.Name = "GOMEZ, MAR B.";
// other employees...
#endregion
employeeList = new List<Employee>
{
employee1,
employee2
};
employeeList.Dump();
}
public class Employee
{
public string EmployeeNo { get; set; }
public string Name { get; set; }
}
You could do this
var list = new List<Employee>
{
new Employee {EmployeeNo = "000001", Name = "Peter Pan"},
new Employee {EmployeeNo = "000002", Name = "King Kong"}
};
of this
public class EmployeeList : List<Employee>
{
public void Add(string no, string name)
{
this.Add(new Employee(no, name));
}
}
var list = new EmployeeList
{
{ "000001", "Peter Pan" },
{ "000002", "King Kong"}
};
You could do something like that
var employee1 = New Employee() { EmployeeNo = "000001", Name = "DELA CRUZ, JUAN T." };
How about this?
void Main()
{
var employeeList = new List<Employee> {
new Employee { EmployeeNo = "000001", Name = "DELA CRUZ, JUAN T." },
new Employee { EmployeeNo = "000002", Name = "GOMEZ, MAR B." }
};
employeeList.Dump();
}
public class Employee
{
public string EmployeeNo { get; set; }
public string Name { get; set; }
}

Categories

Resources