0

I have been doing some research into the fluent API to be able to make this but i am not sure if that is the way to go, from what i understand the OnModelCreate will recreate a DB but what i actually need is a way to relate my tables for my entity, i have a DB with this 2 tables

dbo.Fleets 
OwnerId   (PK,uniqueidentifier,not null) 
ownerName (nvarchar(255),not null)


dbo.UserAccount
UserID        (PK,uniqueidentifier,not null)
UserName      (nchar(20), null)
SelectedFleet (FK,uniqueidentifier,null)
PrimaryFleet  (FK,UniqueIdentifier,null)

The foreign keys are for Fleets.OwnerId, both of them, so inside my application i want to be able to get the fleet for my Primary and SelectedFleet with EF.

so if i run var v = dc.UserAccounts.Where(a => a.UserName == model.UserName).Include(d => d.Fleet).SingleOrDefault(); I'll be getting my complete results

Asif Patel
  • 1,744
  • 1
  • 20
  • 27
pato.llaguno
  • 741
  • 4
  • 20

1 Answers1

-1

I personally prefer to use DataAnnotations.

    [Table("UserAccounts")]
    public class UserAccounts
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string UserName { get; set; }

        public virtual ICollection<Fleets> Fleets { get; set; }
    }

    [Table("Fleets")]
    public class Fleets
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual UserAccounts UserAccount { get; set; }
    }     

Then to access the users fleet you would use

var v = dc.UserAccounts.Where(a => a.UserName == model.UserName).Include(d => d.Fleet).SingleOrDefault();
niko619
  • 433
  • 9
  • 20
  • But how does that solve my problem? I need 2 different fleets per account – pato.llaguno Mar 24 '17 at 03:30
  • So if a UserAccount needs to have many Fleets then this is not a One - One relationship. It becomes a One - Many. I have edited the code to represent that. – niko619 Mar 24 '17 at 12:44
  • Actually its 2 x one to one – pato.llaguno Mar 24 '17 at 13:41
  • @pato.llaguno - From what I understand you have 2 classes, a parent(UserAccounts) and a child(Fleets). From that you want to be able to access the child property after you have successfully located the correct parent based on Id. Is that right? – niko619 Mar 24 '17 at 22:45