1:新建Model类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MVCMusicStore.Models { public class OrderDetail { [Key,Column(Order=1)] public virtual int OrderId { get; set; } [Key, Column(Order = 2)] public virtual int LineNo { get; set; } public virtual string ItemNo { get; set; } public virtual string Description { get; set; } public virtual decimal Price { get; set; } public virtual decimal Quantity { get; set; } public virtual decimal Amount { get; set; } public virtual decimal LineDiscount { get; set; } public virtual decimal LineAmount { get; set; } public virtual Order Order { get; set; } } }
2:创建Controller
3:创建好Controller后,可以看到生成的SQL表主键是由两个字段组成OrderId和LineNo
结论:
1:默认的主键是类的第一个字段;
2:如果需要修改默认的主键字段,需要添加命名空间;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;
3:在类的需要定义为主键的属性上添加Attribute Key和Column修饰
[Key,Column(Order=1)]