Hanna
Hanna

Reputation: 10771

Foreign Keys on Models (code-first)

I have a few models and a database but no foreign keys linking anything together. This seems to be a huge weakness in my project so I'm trying to insert foreign keys into my models and then perhaps regenerating my database based on my models.

I'm having some trouble understanding how the foreign keys work, especially in a one-to-many relationship.

For this example I have a product or products and each product may have multiple reviews:

I've removed some annotations and attributes to condense the models.

Product Model/Entity:

public class Product
    {
        public int ProductId { get; set; }

        public int OwnerId {get; set; }

        public string Title { get; set; }

        public int Rating { get; set; }

        public decimal Price { get; set; }

        public int Quantity { get; set; }

        public string Description { get; set; }
    }

Review Model/Entity:

 public class Review
    {

        public int ReviewId { get; set; }

        public int ProductId { get; set; }

        public int WriterId { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }
    }

I would want a foreign key constraint on the ProductId of Product to the ProductId of review. How would I make this work?

Upvotes: 1

Views: 4094

Answers (2)

Slauma
Slauma

Reputation: 177163

You need at least one navigation property to define a relationship between two entities, for instance:

public class Review
{
    public int ReviewId { get; set; }

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

    public int WriterId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

You can also add a collection property in Product if you want:

public ICollection<Review> Reviews { get; set; }

Instead of using a [ForeignKey] attribute you can define the FK with Fluent API:

modelBuilder.Entity<Review>()
    .HasRequired(r => r.Product)
    .WithMany()  // or .WithMany(p => p.Reviews)
    .HasForeignKey(r => r.ProductId);

Upvotes: 4

Nate
Nate

Reputation: 1

The purpose of a foreign key is to link the tables together. Foreign keys are easy to explain when there is a unique id number for example. The productId should be a unique id and probably the primary key of your product table. In the review table productId is a foreign key because it will allow the tables to be joined and view all categories of data from both tables.

select ProductId, Title, Price, WriterId, Description from Product as P, Review as R where P.ProductId = R.ProductId;

When this select statement is run against ur db you will see the Product unique id, title, price, writer id from the review table, desript. The key line is P.ProductId = R.ProductId

Also make sure that foreign keys are not null

Upvotes: 0

Related Questions