0

I was hoping this would be fairly straight forward but I haven't had much luck. The database I'm working with has a table for users and a table for tokens, they relate to one another with a 1 to 1 relationship with tokens being as I understand it the principal.

public class Token
{
    public int ID { get; set; }
    public string Location { get; set; }

    public virtual User Contact { get; set; }
}

public class User
{
    public int ID { get; set; }
    public int TokenID { get; set; }
    public string Name { get; set; }

    public virtual Token Token { get; set; }
}

So every User has an associated Token which belongs to that User only, and there also also other Tokens that relate to other objects which I will be mapping as well in a similar fashion.

So far I have tried below as well as some variations and it hasn't worked as expected, I keep getting incorrect locations for users as it seems to be using User.ID to map to Token.ID instead of using User.TokenID.

modelBuilder.Entity<User>()
    .HasRequired(p => p.Token)
    .WithOptional(p => p.Contact);

I'm thinking I'm missing actually specifying the columns to use to map? I'm just unsure where to go from here.

Edit Previously when mapping relationships that use the WithRequired() extension method I've then been able to specify HasForeignKey() afterwards but WithOptional() doesn't seem to have this functionality.

Alex.Ritna
  • 1,957
  • 2
  • 16
  • 24
  • 1
    If they're 1-1, I think EF expects them to share a primary key. – mcalex Oct 19 '12 at 00:10
  • Perhaps I phrased my question incorrectly, the relationship is such that each User has a required TokenID, but Tokens may be associated with other Objects not just Users. Does this make it a "1 to 0 or 1"? If so how would I map that correctly? – Alex.Ritna Oct 19 '12 at 00:16
  • yeah, if a Token doesn't have to have a User it's a 1-0:1 relationship. This might help: http://stackoverflow.com/questions/6021135/ef-code-first-1-to-1-optional-relationship – mcalex Oct 19 '12 at 06:46

1 Answers1

0

I have a solution that isn't ideal, but it is working OK for me at the moment.

I have changed the models and mappings as detailed below, specifying a 1 to many relationship even though that isn't really the case.

public class Token
{
    public int ID { get; set; }
    public string Location { get; set; }

    public virtual List<User> Contact { get; set; }
}

public class User
{
    public int ID { get; set; }
    public int TokenID { get; set; }
    public string Name { get; set; }

    public virtual Token Token { get; set; }
}

Then this mapping.

modelBuilder.Entity<User>()
    .HasRequired(u => u.Token)
    .WithMany(t => t.Contact)
    .HasForeignKey(u => u.TokenID);
Alex.Ritna
  • 1,957
  • 2
  • 16
  • 24