如何通过CodeFirst模式为EF实体类添加复合主键?

2026-03-30 10:531阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计227个文字,预计阅读时间需要1分钟。

如何通过CodeFirst模式为EF实体类添加复合主键?

csharpusing System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Web;namespace MyFirstMvcApp.Models{ /// /// 登录记录 /// }

using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace MyFirstMvcApp.Models { /// <summary> /// 登录记录 /// </summary> public class LoginRecordInfo { /// <summary> /// 登录的邮件地址(主键) /// </summary> [Key,Column(Order=1)] public string Email { get; set; } /// <summary> /// 登录的客户端IP /// </summary> public string LoginHostIP { get; set; } /// <summary> /// 登录的客户端主机名 /// </summary> public string LoginHostName { get; set; } /// <summary> /// 登录时间(主键) /// </summary> [Key,Column(Order=2)] public DateTime LoginTime { get; set; } } }

使用特性Key和Column设置复合主键,Key表示字段是主键,Order用来设置主键的顺序。使用Key和Column需要添加命名空间:

如何通过CodeFirst模式为EF实体类添加复合主键?

  • Key的命名空间:System.ComponentModel.DataAnnotations;
  • Column的命名空间:System.ComponentModel.DataAnnotations.Schema;

到此这篇关于EF使用Code First模式给实体类添加复合主键的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持自由互联。

本文共计227个文字,预计阅读时间需要1分钟。

如何通过CodeFirst模式为EF实体类添加复合主键?

csharpusing System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Web;namespace MyFirstMvcApp.Models{ /// /// 登录记录 /// }

using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace MyFirstMvcApp.Models { /// <summary> /// 登录记录 /// </summary> public class LoginRecordInfo { /// <summary> /// 登录的邮件地址(主键) /// </summary> [Key,Column(Order=1)] public string Email { get; set; } /// <summary> /// 登录的客户端IP /// </summary> public string LoginHostIP { get; set; } /// <summary> /// 登录的客户端主机名 /// </summary> public string LoginHostName { get; set; } /// <summary> /// 登录时间(主键) /// </summary> [Key,Column(Order=2)] public DateTime LoginTime { get; set; } } }

使用特性Key和Column设置复合主键,Key表示字段是主键,Order用来设置主键的顺序。使用Key和Column需要添加命名空间:

如何通过CodeFirst模式为EF实体类添加复合主键?

  • Key的命名空间:System.ComponentModel.DataAnnotations;
  • Column的命名空间:System.ComponentModel.DataAnnotations.Schema;

到此这篇关于EF使用Code First模式给实体类添加复合主键的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持自由互联。