Question

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?

Was it helpful?

Solution

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; }
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top