c# - One to many with additional properties in Entity Framework -


i new ef , have got basic question. can please advise how implement below scenario using code first approach ?

    public class book     {        public int id {get; set;}        public string title {get; set;}        public string author {get; set;}        public datetime dateborrowed {get; set;}        public datetime datereturned {get; set;}         public virtual user borrower {get;set;}     }     public class user     {        public int id {get;set;}        public string username {get;set;}        public string email {get; set;}         public virtual icollection<book> books {get; set;}     } 

i maintain both book , user classes/underlying tables maintain unique collection of records every time. in other words, how separate dateborrowed , datereturned properties in separate class book borrowing , returning transactions maintained in separate sql table.

current setup allow each book have 1 single record of when borrowed , when returned. every time borrowed or returned, overwrite last one. you're looking more along lines creating class holds 2 dates, , reference class foreign key in book table.

your current table may change (code not tested):

public class book {    public int bookid {get; set;}    public string title {get; set;}    public string author {get; set;}     public virtual icollection<borrowingrecord> borrowingrecords { get; set; }     public int userid { get; set; }    public virtual user borrower {get;set;} }  public class borrwingrecord {     public int borrowingrecordid {get; set; }     public datetime dateborrowed {get; set;}     public datetime datereturned {get; set;}      public int bookid { get; set; }     public virtual book book { get; set; } }  public class user {    public int userid {get;set;}    public string username {get;set;}    public string email {get; set;}     public virtual icollection<book> books {get; set;} } 

you have right idea user table. set connections , you're go.

what you're looking one-to-many relationship. consult page more detail on it: https://msdn.microsoft.com/en-us/data/jj713564.aspx

here's example of how you'd books borrowed given user , borrowing record of books (code not tested , assumes you've set context):

var booksforuser = context.books.where(b => b.userid == givenuserid);  foreach(var book in booksforuser) {     var borrowingrecordforbook = context.borrowingrecords.where(br => br.bookid == book.bookid);      // need data. } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -