无法首先使用 entity framework 代码将其他指定的列而不是 Id 列设置为 table 的主键

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

我有两个table ProductOrder

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
}

我用过下面的代码先用代码

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

获取异常

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.

EF 仅支持属性,因此您应该将字段更改为属性。当您这样做时,使用 {class Name} + Id 作为 属性 名称,按照惯例它将被选为键 属性。或者,您可以在 属性 上使用 [Key] 属性让 EF 知道它应该是键 属性。您可以找到有关 EF 属性的更多信息 here.