locked
How to make a non integer key in many-to-many relationship RRS feed

  • Question

  • I'm creating an online card game and learning entity framework while at it.

    I have a class Accounts (with ID, Username, Password) and a class Card (with ID, Cost, Name). Now I want a class (table) CardsByAccount, that has an Account, a Card and an amount (how many of this card an account has).

    Since I want to stay as OO as possible I first tried this:

            [Key]
            public Account Account { get; set; }
    
            public byte Amount { get; set; }
    
            [Key]
            public Card Card { get; set; }

    but I get a ModelValidationException. It seems this is not allowed.

    I could make it work by changing it to this:

            public Account Account { get; set; }
    
            public byte Amount { get; set; }
    
            public Card Card { get; set; }
    
            public int ID { get; set; }

    but I don't like this, since the extra key is redundant. The combination of Account and Card should be enough for key. I also don't feel like adding int AccountID and int CardID, because I reference the right objects already.

    Are there other ways to implement this?

    Thanks in advance,

    P.

    Wednesday, September 2, 2015 11:19 AM

Answers

  • I think you might have to do something like this:

        [Key, Column(Order = 0)]
        public int AccountID { get; set; }
        [Key, Column(Order = 1)]
        public int CardID { get; set; }
    
        public virtual Account Account { get; set; }
        public virtual Card Card { get; set; }
    
        public byte Amount { get; set; }

    I know that the column order must be specified when using multiple keys.  

    And I'm not sure, but I think they might have to be scalars as well, hence breaking out the ids separately.

    • Marked as answer by Persipnei.net Wednesday, September 2, 2015 2:59 PM
    Wednesday, September 2, 2015 1:06 PM

All replies

  • I think you might have to do something like this:

        [Key, Column(Order = 0)]
        public int AccountID { get; set; }
        [Key, Column(Order = 1)]
        public int CardID { get; set; }
    
        public virtual Account Account { get; set; }
        public virtual Card Card { get; set; }
    
        public byte Amount { get; set; }

    I know that the column order must be specified when using multiple keys.  

    And I'm not sure, but I think they might have to be scalars as well, hence breaking out the ids separately.

    • Marked as answer by Persipnei.net Wednesday, September 2, 2015 2:59 PM
    Wednesday, September 2, 2015 1:06 PM
  • Thank you, this works like a charm, although I hoped for a way without extra int-properties, since Account and Card already contain those values.

    Wednesday, September 2, 2015 3:01 PM