排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
分类:
EF
实体对象进行关联(给学生表定义外键)
//学生表实体 public partial class UserInfo { [Key] public int Sid { get; set; } [StringLength(16,MinimumLength=2)] [Required, Column("UserName")] public string UserName { get; set; } [StringLength(10, MinimumLength = 2)] [Required, Column("UserNum")] public string UserNum { get; set; } //自定义字段外键 [ForeignKey("parent")] public int Fid { get; set; } //导航属性 public virtual Parents parent { get; set; } } //家长表 public class Parents { [Key] public int Sid { get; set; } [StringLength(16, MinimumLength = 2)] [Required, Column("Father")] public string Father { get; set; } [StringLength(16, MinimumLength = 2)] [Required, Column("Mather")] public string Mather { get; set; } [Required, Column("Uid")] public int Uid { get; set; } //导航属性 public virtual List<UserInfo> userinfo { get; set; } }
上下文对象重写添加外键
//重写方法 protected override void OnModelCreating(DbModelBuilder modelBuilder) { //绑学生表的Fid字段为外键 modelBuilder.Entity<UserInfo>().HasRequired(a => a.parent).WithMany(a =>a.userinfo).HasForeignKey(a=>a.Fid); } //或者 protected override void OnModelCreating(DbModelBuilder modelBuilder) { //绑学生表的Fid字段为外键 modelBuilder.Entity<Parents>().HasMany(a=>a.userinfo).WithRequired(a=>a.parent).HasForeignKey(a=>a.Fid) }
评价