How to have navigation properties without a database - c#

I am building an app with NO persistence data. So it will be in memory.
I have the following POCO entities
public class Book
{
public Book()
{
BorrowedBooks = new List<BorrowedBooks>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public virtual ICollection<BorrowedBooks> BorrowedBooks { get; set; }
}
public class Borrower
{
public Borrower()
{
BorrowedBooks = new List<BorrowedBooks>();
}
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public virtual ICollection<BorrowedBooks> BorrowedBooks { get; set; }
}
public class BorrowedBooks
{
public int Id { get; set; }
public int BookId { get; set; }
public int BorrowerId { get; set; }
public DateTime DateBorrowed { get; set; }
public virtual Book Book { get; set; }
public virtual Borrower Borrower { get; set; }
}
I have created a class that will populated some sample data
public class DemoData
{
static Book book1 = new Book { Id = 1, Title = "Queen of the road", Author = "Tricia Stringer" };
static Book book2 = new Book { Id = 2, Title = "Don't look now", Author = "Paul Jennings" };
static Book book3 = new Book { Id = 3, Title = "Too bold to die", Author = "Ian McPhedran" };
static Book book4 = new Book { Id = 4, Title = "The rosie project", Author = "Graeme Simson" };
static Book book5 = new Book { Id = 5, Title = "In great spirits", Author = "Archie Barwick" };
static Book book6 = new Book { Id = 6, Title = "The vale girl", Author = "Nelika Mcdonald" };
static Book book7 = new Book { Id = 7, Title = "Watching you", Author = "Michael Robotham" };
static Book book8 = new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" };
static Borrower borrower1 = new Borrower { Id = 1, Firstname = "John", Lastname = "Smith" };
static Borrower borrower2 = new Borrower { Id = 2, Firstname = "Mary", Lastname = "Jane" };
static Borrower borrower3 = new Borrower { Id = 3, Firstname = "Peter", Lastname = "Parker" };
static Borrower borrower4 = new Borrower { Id = 4, Firstname = "Eddie", Lastname = "Brock" };
static BorrowedBooks borrowed1 = new BorrowedBooks { BookId = 8, Book = book8, BorrowerId = 2, Borrower=borrower2, DateBorrowed = DateTime.Parse("01/04/2014") };
static BorrowedBooks borrowed2 = new BorrowedBooks {BookId = 6, Book = book6, BorrowerId = 4, Borrower = borrower4, DateBorrowed = DateTime.Parse("08/04/2014")};
static BorrowedBooks borrowed3 = new BorrowedBooks { BookId = 2, Book = book2, BorrowerId = 4, Borrower = borrower4, DateBorrowed = DateTime.Parse("08/04/2014") };
static BorrowedBooks borrowed4 = new BorrowedBooks { BookId = 1, Book = book1, BorrowerId = 1, Borrower = borrower1, DateBorrowed = DateTime.Parse("26/03/2014") };
public List<BorrowedBooks> borrowedBooks = new List<BorrowedBooks>
{
borrowed1, borrowed2, borrowed3, borrowed4
};
public List<Book> books = new List<Book>
{
book1, book2, book3, book4, book5, book6, book7, book8
};
private List<Borrower> borrowers = new List<Borrower>
{
borrower1, borrower2, borrower3, borrower4
};
}
data access code
public class BookRepository : IBookRepository
{
private DemoData data = new DemoData();
public bool Add(Book book)
{
try
{
this.data.books.Add(book);
}
catch (Exception ex)
{
return false;
}
return true;
}
public bool BorrowBook(BorrowedBooks details)
{
try
{
this.data.borrowedBooks.Add(details);
}
catch (Exception ex)
{
return false;
}
return true;
}
public IEnumerable<Book> Search()
{
return data.books;
}
}
controller code
public class BookController : Controller
{
private IBookRepository _bookRepo;
public BookController(IBookRepository bookRepo)
{
_bookRepo = bookRepo;
}
public ActionResult Search()
{
var test = _bookRepo.Search();
return View(test);
}
}
But when I get the data from the repository, the navigation properties are empty... what am I doing wrong?

You need to fill collections for books in DemoData. If you don't set them yourself they are null. So in short if you don't use any persistence framework you must create relations from both sides.
For example for book1 you'll need to add:
book1.BorrowedBooks.Add(borrowed4);
And so on for all collections in all entities in your in memory database.

I think you need to make your lists static in the DemoData class as well and remove the instance private members of DemoData from you repositories. That way all your repositories will use the same data.
public static class DemoData
{
static Book book1 = new Book { Id = 1, Title = "Queen of the road", Author = "Tricia Stringer" };
static Book book2 = new Book { Id = 2, Title = "Don't look now", Author = "Paul Jennings" };
static Book book3 = new Book { Id = 3, Title = "Too bold to die", Author = "Ian McPhedran" };
static Book book4 = new Book { Id = 4, Title = "The rosie project", Author = "Graeme Simson" };
static Book book5 = new Book { Id = 5, Title = "In great spirits", Author = "Archie Barwick" };
static Book book6 = new Book { Id = 6, Title = "The vale girl", Author = "Nelika Mcdonald" };
static Book book7 = new Book { Id = 7, Title = "Watching you", Author = "Michael Robotham" };
static Book book8 = new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" };
static Borrower borrower1 = new Borrower { Id = 1, Firstname = "John", Lastname = "Smith" };
static Borrower borrower2 = new Borrower { Id = 2, Firstname = "Mary", Lastname = "Jane" };
static Borrower borrower3 = new Borrower { Id = 3, Firstname = "Peter", Lastname = "Parker" };
static Borrower borrower4 = new Borrower { Id = 4, Firstname = "Eddie", Lastname = "Brock" };
static BorrowedBooks borrowed1 = new BorrowedBooks { BookId = 8, Book = book8, BorrowerId = 2, Borrower=borrower2, DateBorrowed = DateTime.Parse("01/04/2014") };
static BorrowedBooks borrowed2 = new BorrowedBooks {BookId = 6, Book = book6, BorrowerId = 4, Borrower = borrower4, DateBorrowed = DateTime.Parse("08/04/2014")};
static BorrowedBooks borrowed3 = new BorrowedBooks { BookId = 2, Book = book2, BorrowerId = 4, Borrower = borrower4, DateBorrowed = DateTime.Parse("08/04/2014") };
static BorrowedBooks borrowed4 = new BorrowedBooks { BookId = 1, Book = book1, BorrowerId = 1, Borrower = borrower1, DateBorrowed = DateTime.Parse("26/03/2014") };
public static List<BorrowedBooks> borrowedBooks = new List<BorrowedBooks>
{
borrowed1, borrowed2, borrowed3, borrowed4
};
public static List<Book> books = new List<Book>
{
book1, book2, book3, book4, book5, book6, book7, book8
};
private static List<Borrower> borrowers = new List<Borrower>
{
borrower1, borrower2, borrower3, borrower4
};
}
Then in your book repository, you access via the static members rather than an instance field.
public class BookRepository : IBookRepository
{
public bool Add(Book book)
{
try
{
DemoData.books.Add(book);
}
catch (Exception ex)
{
return false;
}
return true;
}
public bool BorrowBook(BorrowedBooks details)
{
try
{
DemoData.borrowedBooks.Add(details);
}
catch (Exception ex)
{
return false;
}
return true;

Related

Copy add or combine a model

I am having problem adding to the model. I want to have a list in the Root1 or in the Viewmodel like fullname and authors list.
newModel1
AuthorsAccepted count=4
FullName = Jack
AuthorsAccepted count=4
FullName = Time Dean
With the code below it only adds the last one to the Root1. I created a a third model. Is there a way I can add to the third model both the lists or in Root1.
var fullName = "Jack";
var fullName2 = "Tim Dean";
var authors1 = new List<AuthorsAccepted1>() {
new AuthorsAccepted1(){ id = 1, Name="Bill"},
new AuthorsAccepted1(){ id = 2, Name="Steve"},
new AuthorsAccepted1(){ id = 3, Name="jon"},
new AuthorsAccepted1(){ id = 4, Name="nick"}
};
var authors2 = new List<AuthorsAccepted1>() {
new AuthorsAccepted1(){ id = 1, Name="jack"},
new AuthorsAccepted1(){ id = 2, Name="tim"},
new AuthorsAccepted1(){ id = 3, Name="james"},
new AuthorsAccepted1(){ id = 4, Name="mary"}
};
var newModel1 = new Root1();
newModel1.FullName = fullName;
newModel1.AuthorsAccepted = authors1;
var newModel2 = new Root1();
newModel2.FullName = fullName2;
newModel2.AuthorsAccepted = authors2;
}
}
public class Root1
{
public string FullName { get; set; }
public List<AuthorsAccepted1> AuthorsAccepted { get; set; }
}
public class AuthorsAccepted1
{
public string Name { get; set; }
public int id { get; set; }
}
public class Viewmodel
{
public Root1 AllModel { get; set; }
}

Remove from a list that has a list within it based on integer list

I have a list that basically look like this...
public class Area
{
public int Id { get; set; }
public string Name { get; set; }
public List<ZipCodeAdresses> ListOfIncludedDestinations { get; set; }
}
public class ZipCodeAdresses
{
public int AreaId { get; set; }
public List<Person> AdressList { get; set; }
}
public class Person
{
public string MottagarNamn { get; set; }
public string Street { get; set; }
}
var intListToRemove = new List<int>(){2,3};
var list = new List<Area>();
var subList = new List<ZipCodeAdresses>();
var personList = new List<Person>
{
new Person() {MottagarNamn = "User 1"},
new Person() {MottagarNamn = "User 2"}
};
subList.Add(new ZipCodeAdresses(){AdressList = personList , AreaId = 1});
personList = new List<Person>
{
new Person() {MottagarNamn = "User 3"},
new Person() {MottagarNamn = "User 4"}
};
subList.Add(new ZipCodeAdresses() { AdressList = personList, AreaId = 2 });
list.Add(new Area(){Name = "List A", ListOfIncludedDestinations = subList});
subList = new List<ZipCodeAdresses>();
personList = new List<Person>
{
new Person() {MottagarNamn = "User 5"},
new Person() {MottagarNamn = "User 6"}
};
subList.Add(new ZipCodeAdresses() { AdressList = personList, AreaId = 3 });
personList = new List<Person>
{
new Person() {MottagarNamn = "User 7"},
new Person() {MottagarNamn = "User 8"}
};
subList.Add(new ZipCodeAdresses() { AdressList = personList, AreaId = 4 });
list.Add(new Area() { Name = "List B", ListOfIncludedDestinations = subList });
I need to be able to remove from the list ListOfIncludedDestinations where AreaId is equal to any integer in intListToRemove which in this example is 2 and 3?
List<T> contains a method RemoveAll, that removes all entries that fulfill a certain condition. In your case it is:
foreach(var entry in list)
{
entry.ListOfIncludedDestinations.RemoveAll(x => intListToRemove.Contains(x.AreaId));
}
This loops through your list, and for every entry it removes all entries in ListOfIncludedDestinations that have an AreadId which is in intListToRemove.
Online demo: https://dotnetfiddle.net/ialnPb
You should add this sample code to remove them from the list :
foreach (var i in list)
i.ListOfIncludedDestinations.RemoveAll(o => intListToRemove.Contains(o.AreaId));

How to order parent object by child sub object

i have a List< PaperAbstract > class. a PaperAbstract class has a set of Authors. one of the Authors has a flag IsSubmitting true. how can i order my List< PaperAbstract > by the submitting authors LastName?
public class PaperAbstract
{
public string Title { get; set; }
public List<Author> Authors { get; set; }
}
public class Author
{
public bool IsSubmitting { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
for example:
var paperAbstracts = new List<PaperAbstract>();
paperAbstracts.Add(new PaperAbstract
{
Title = "Abstract 2",
Authors = new List<Author>
{
new Author { IsSubmitting = false, FirstName = "F5", LastName = "L5"},
new Author { IsSubmitting = true, FirstName = "F6", LastName = "L6"}
}
});
paperAbstracts.Add(new PaperAbstract
{
Title = "Abstract 3",
Authors = new List<Author>
{
new Author { IsSubmitting = true, FirstName = "F1", LastName = "L1"},
new Author { IsSubmitting = false, FirstName = "F2", LastName = "L2"}
}
});
paperAbstracts.Add(new PaperAbstract
{
Title = "Abstract 1",
Authors = new List<Author>
{
new Author { IsSubmitting = false, FirstName = "F3", LastName = "L3"},
new Author { IsSubmitting = true, FirstName = "F4", LastName = "L4"}
}
});
the correct order of paperAbstracts should be Abstract 3, Abstract 1, Abstract 2.
You can use OrderBy from LINQ:
var result = input.OrderBy(x => x.Authors
.First(a => a.IsSubmitting).LastName)

How to setup with navigation properties

I am trying to set up a simple library application in MVC4
I have the following entities
public class Book
{
public Book()
{
BorrowedBooks = new List<BorrowedBooks>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public virtual ICollection<BorrowedBooks> BorrowedBooks { get; set; }
}
public class Borrower
{
public Borrower()
{
BorrowedBooks = new List<BorrowedBooks>();
}
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public virtual ICollection<BorrowedBooks> BorrowedBooks { get; set; }
}
public class BorrowedBooks
{
public int Id { get; set; }
public int BookId { get; set; }
public int BorrowerId { get; set; }
public DateTime DateBorrowed { get; set; }
public virtual Book Book { get; set; }
public virtual Borrower Borrower { get; set; }
}
I have setup 2 repositories
public class BookRepository : IBookRepository
{
private List<Book> books = new List<Book>
{
new Book { Id = 1, Title = "Queen of the road", Author = "Tricia Stringer", BorrowedBooks = new List<BorrowedBooks>{ new BorrowedBooks {BookId = 1, BorrowerId = 1, DateBorrowed = DateTime.Parse("26/03/2014")}} },
new Book { Id = 2, Title = "Don't look now", Author = "Paul Jennings" },
new Book { Id = 3, Title = "Too bold to die", Author = "Ian McPhedran" },
new Book { Id = 4, Title = "The rosie project", Author = "Graeme Simson" },
new Book { Id = 5, Title = "In great spirits", Author = "Archie Barwick" },
new Book { Id = 6, Title = "The vale girl", Author = "Nelika Mcdonald" },
new Book { Id = 7, Title = "Watching you", Author = "Michael Robotham" },
new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" },
};
private List<BorrowedBooks> borrowedBooks = new List<BorrowedBooks>
{
new BorrowedBooks {BookId = 8, Book = new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" }, BorrowerId = 2, DateBorrowed = DateTime.Parse("01/04/2014")},
new BorrowedBooks {BookId = 6, BorrowerId = 4, DateBorrowed = DateTime.Parse("08/04/2014")},
new BorrowedBooks {BookId = 2, BorrowerId = 4, DateBorrowed = DateTime.Parse("08/04/2014")},
new BorrowedBooks {BookId = 1, BorrowerId = 1, DateBorrowed = DateTime.Parse("26/03/2014")},
};
public IEnumerable<Book> Search()
{
return books;
}
}
public class BorrowerRepository : IBorrowerRepository
{
private List<Borrower> borrowers = new List<Borrower>
{
new Borrower { Id = 1, Firstname = "John", Lastname = "Smith" },
new Borrower { Id = 2, Firstname = "Mary", Lastname = "Jane" },
new Borrower { Id = 3, Firstname = "Peter", Lastname = "Parker" },
new Borrower { Id = 4, Firstname = "Eddie", Lastname = "Brock" },
};
public void Add(Borrower borrower)
{
this.borrowers.Add(borrower);
}
}
How do I link the properties together? ie in my BorrowerRepository search method, it return all the data, but the Book value is just an ID, how do I link it with the values from the book repository?
have I set up my navigation property wrong? or is it the way I have set up my Repository data?
One way to achieve that is to add a static class to hold collections of your data in memory.
Then in each of your repositories you delegate any data related operation to the appropriate collections in the data store and you can use Linq to do your queries.
public static class DataStore
{
private static List<Book> books = new List<Book>
{
new Book { Id = 1, Title = "Queen of the road", Author = "Tricia Stringer", BorrowedBooks = new List<BorrowedBooks>{ new BorrowedBooks {BookId = 1, BorrowerId = 1, DateBorrowed = DateTime.Parse("26/03/2014")}} },
new Book { Id = 2, Title = "Don't look now", Author = "Paul Jennings" },
new Book { Id = 3, Title = "Too bold to die", Author = "Ian McPhedran" },
new Book { Id = 4, Title = "The rosie project", Author = "Graeme Simson" },
new Book { Id = 5, Title = "In great spirits", Author = "Archie Barwick" },
new Book { Id = 6, Title = "The vale girl", Author = "Nelika Mcdonald" },
new Book { Id = 7, Title = "Watching you", Author = "Michael Robotham" },
new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" },
};
private static List<BorrowedBooks> borrowedBooks = new List<BorrowedBooks>
{
new BorrowedBooks {BookId = 8, Book = new Book { Id = 8, Title = "Stillways", Author = "Steve Bisley" }, BorrowerId = 2, DateBorrowed = DateTime.Parse("01/04/2014")},
new BorrowedBooks {BookId = 6, BorrowerId = 4, DateBorrowed = DateTime.Parse("08/04/2014")},
new BorrowedBooks {BookId = 2, BorrowerId = 4, DateBorrowed = DateTime.Parse("08/04/2014")},
new BorrowedBooks {BookId = 1, BorrowerId = 1, DateBorrowed = DateTime.Parse("26/03/2014")},
};
private static List<Borrower> borrowers = new List<Borrower>
{
new Borrower { Id = 1, Firstname = "John", Lastname = "Smith" },
new Borrower { Id = 2, Firstname = "Mary", Lastname = "Jane" },
new Borrower { Id = 3, Firstname = "Peter", Lastname = "Parker" },
new Borrower { Id = 4, Firstname = "Eddie", Lastname = "Brock" },
};
public static List<Book> Books { get { return books; } }
public static List<BorrowedBooks> BorrowedBooks { get { return borrowedBooks; } }
public static List<Borrower> Borrowers { get { return borrowers; } }
}
public class BookRepository : IBookRepository
{
public IEnumerable<Book> Search()
{
return DataStore.Books.Where (b => b.Author == "Paul Jennings");
}
}
public class BorrowerRepository : IBorrowerRepository
{
public void Add(Borrower borrower)
{
DataStore.Borrowers.Add(borrower);
}
}

Flatten LINQ Collection

I have had a look at this Flatten LINQ collection object with nested object collections but it doesn't quite do it for me.
I know there is a lot of code in this post but it's mostly just data to give you the idea of what I'm looking at developing.
if you look at the classes below, I am trying to come up with a way to flatten the result of a search against the file.
So i need to end up with a single flattened record which looks like (the pipes are there to show delimination of a field only)
fileId | FileContact1FirstName | FileContact1LastName | FileContact2FirstName etc | FileClient1FirstName | FileClient1LastName | FileClient1IsNominee | FileClient1IsPrimary | FileClient2FirstName etc....
Any idea on how I can do this without looping through each Contact and Client?
I have these classes of sorts in my edmx;
class File
{
public int fileId { get; set; }
public List<FileContact> fileContacts { get; set; }
public List<FileClient> fileClients { get; set; }
}
class FileContact
{
public Contact contact { get; set; }
}
class FileClient
{
public Contact contact { get; set; }
public bool IsNominee { get; set; }
public bool IsPrimary { get; set; }
}
class Contact
{
public int id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
And this this as the data simply for testing.
static void FillData()
{
thisFile = new File { fileId = 1, fileContacts = new List<FileContact>(), fileClients = new List<FileClient>() };
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Andrew", lastName = "Albino" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Bob", lastName = "Bush" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Cathy", lastName = "Conti" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Drew", lastName = "Dram" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Edward", lastName = "Eliston" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Frank", lastName = "Fashion" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Graham", lastName = "Grape" } });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Harry", lastName = "Who didn't" }, IsNominee = true, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Indigo", lastName = "Ignacio" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Julie", lastName = "Juniper" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Kelly", lastName = "Keilor" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Liam", lastName = "Loser" }, IsNominee = false, IsPrimary = true });
}
}
This will get you an IEnumerable<string> that contains the properties in the order you specified:
var flattened = new string[] { thisFile.fileId.ToString() }
.Concat(
thisFile.fileContacts
.SelectMany(fc => new string[]
{
fc.contact.firstName,
fc.contact.lastName
}))
.Concat(
thisFile.fileClients
.SelectMany(fc => new string[]
{
fc.contact.firstName,
fc.contact.lastName,
fc.IsNominee.ToString(),
fc.IsPrimary.ToString()
}));
Example: http://ideone.com/Mvc7M
Have a look at SelectMany.

Categories

Resources