Entity Framework中的實體類添加復合主鍵


使用Code First模式實現給實體類添加復合主鍵,代碼如下:

復制代碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.ComponentModel.DataAnnotations.Schema;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace MyFirstMvcApp.Models
 9 {
10     /// <summary>
11     /// 登錄記錄
12     /// </summary>
13     public class LoginRecordInfo
14     {
15         /// <summary>
16         /// 登錄的郵件地址(主鍵)
17         /// </summary>
18         [Key,Column(Order=1)]
19         public string Email { get; set; }
20 
21         /// <summary>
22         /// 登錄的客戶端IP
23         /// </summary>
24         public string LoginHostIP { get; set; }
25 
26         /// <summary>
27         /// 登錄的客戶端主機名
28         /// </summary>
29         public string LoginHostName { get; set; }
30 
31         /// <summary>
32         /// 登錄時間(主鍵)
33         /// </summary>
34         [Key,Column(Order=2)]
35         public DateTime LoginTime { get; set; }
36     }
37 }
復制代碼

使用特性Key和Column設置復合主鍵,Key表示字段是主鍵,Order用來設置主鍵的順序。使用Key和Column需要添加命名空間:
Key的命名空間:System.ComponentModel.DataAnnotations;
Column的命名空間:System.ComponentModel.DataAnnotations.Schema;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM