0

I can't make a simple foreign key relationship in MVC WEB API. I am very confused of how it works. I'm quite confused now after several hours of trying to get this to work.

I have 3 model classes: Task, TaskSubtype and Account

Tasksubtype have a accountID and TaskSubtypeId on creation:

public class Task
{

    public int id { get; set; }
    [Key]
    public Guid TaskId { get; set; }
    [ForeignKey("TaskSubType")]
    public  Guid TaskSubTypeId { get; set; }
    [ForeignKey("Account")]
    public  Guid UserId { get; set; }
}

 public class Account
    {   
        public int Id { get; set; }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid UserId { get; set; }

    }

   public class TaskSubType
    {

        public int id { get; set; }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid SubTaskID { get; set; }
        public String Name { get; set; }


    }

What have I done wrong?

Jason Roell
  • 6,679
  • 4
  • 21
  • 28
Timsen
  • 4,066
  • 10
  • 59
  • 117

2 Answers2

1

There is a great answer Here.

But basically: say for instance if you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let Entity Framework know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}
Community
  • 1
  • 1
Jason Roell
  • 6,679
  • 4
  • 21
  • 28
  • This would defenetly work, but the problem is that i want a Guid which can refer to Accounts for example. The problem ive got is that i only getting a Guid sent back from frontend, so this approach wouldnt work because ModelState.IsValid in MVC will always return false because an object is not a GUID. – Timsen Feb 09 '14 at 23:58
0

If you want to use id as record identifier, do not use GUID for that purpose (or vice-versa). Like this (assuming you are using EF Code First):

public class Task
{

    [Key]
    public int id { get; set; }

    [ForeignKey("TaskSubTypeId")]
    public  int TaskSubTypeId { get; set; }

    [ForeignKey("AccountId ")]
    public  int AccountId { get; set; }
}

public class Account
{   
    [Key]
    public int Id { get; set; }

}

public class TaskSubType
{

    [Key]
    public int id { get; set; }
    public String Name { get; set; }

}

Hope this helps

Khalique Rehman
  • 127
  • 2
  • 7
  • why not using guid ofr that purpose? – Timsen Feb 10 '14 at 20:00
  • Because you already using an identifier which you are calling id in your class. As I understand, Code First convention treats such a column (whose name is id) as identifier. If you want to use GUID that is fine too but then remove id column. Think about it; why would you name a column id when it is not an identifier? – Khalique Rehman Feb 10 '14 at 22:28