Neo
Neo

Reputation: 16219

unable to set other specified column as primary key instead of Id column to table using entity framework code first

I have two table Product and Order

public class Product
{
 string name;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid  productId { get; set; } // i want this to be primary key instead default Id
}

public class Order
{
 string name;
 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid  orderId { get; set; } // i want this to be primary key instead default Id and also want to add productId inside this table as foreign key
}

I have used following code to use code first.

DatabaseContext.cs

  class DatabaseContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }
    }

Program.cs

 static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<DatabaseContext>());

            using (var context = new DatabaseContext())
            {
                context.Product.Add(new Product() {  Name = "mytest" });
                context.SaveChanges();
            }

            Console.WriteLine("Database Created!!!");
            Console.ReadKey();
        }

getting exception

Additional information: Unable to determine composite primary key ordering for type '.Customer'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys.

Upvotes: 0

Views: 569

Answers (1)

Pawel
Pawel

Reputation: 31610

EF supports only properties so you should change your fields to properties. When you do that use {class Name} + Id as the property name and it will be picked up as the key property by convention. Alternatively you can use the [Key] attribute on a property to let EF know it should be the key property. You can find more about EF attributes here.

Upvotes: 1

Related Questions