首页 > 代码库 > EF外键关联
EF外键关联
客户里面存在客服外键
基类模型
public class ModelBase { public ModelBase() { CreateTime = DateTime.Now; } [Key] public virtual int ID { get; set; } public virtual DateTime CreateTime { get; set; } }
客服模型
[Table("CustomerServer")] public partial class CustomerServer : ModelBase { public string ServerId { get; set; } public string ServerName { get; set; } public string Email { get; set; } public string Mobile { get; set; } public virtual List<Customer> CustomerManagerFor { get; set; }}
客户模型
[Table("Customer")] public class Customer : ModelBase { [Required(ErrorMessage = "分支编号不能为空!"), MaxLength(4, ErrorMessage = "分支编号不能超过4个字符!")] public string BranchId { get; set; } [Required(ErrorMessage = "客户编号不能为空!"), MaxLength(10, ErrorMessage = "客户编号不能超过10个字符!")] public string CustomerId { get; set; } [Required(ErrorMessage = "客户姓名不能为空!"), MaxLength(50, ErrorMessage = "客户姓名不能超过50个字符!")] public string Name { get; set; } [Required(ErrorMessage = "性别不能为空!")] public int Sex { get; set; } [Required(ErrorMessage = "生日不能为空!")] public DateTime Birthday { get; set; } [Required(ErrorMessage = "资金账号不能为空!"), MaxLength(40, ErrorMessage = "资金账号不能超过40个字符!")] public string FundAccount { set; get; } [Required(ErrorMessage = "资产不能为空!")] public decimal Assets { get; set; } [Required(ErrorMessage = "联系方式不能为空!"), MaxLength(40, ErrorMessage = "联系方式不能超过40个字符!")] public string Contact { get; set; } [Required(ErrorMessage = "地级市不能为空!")] public int City { get; set; } [InverseProperty("CustomerManagerFor")] [Required(ErrorMessage = "客户经理不能为空!")] public virtual CustomerServer CustomerManager { get; set; } [Required(ErrorMessage = "开户日期不能为空!")] public DateTime OpeningDate { get; set; } [Required(ErrorMessage = "风险类型不能为空!")] public int RiskType { get; set; } [Required(ErrorMessage = "客户类型不能为空!")] public int CustomerType { get; set; } } [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value) { //校验数据库是否存在当前Key return true; } }
在上下文进行映射
protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<CrmDbContext>(null); base.OnModelCreating(modelBuilder); modelBuilder.Entity<Customer>().HasRequired(v => v.CustomerManager).WithMany(d => d.CustomerManagerFor).Map(v => v.MapKey("CustomerManager")).WillCascadeOnDelete(false); }
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerServer> CustomerServers { get; set; }
查询
IQueryable<Customer> queryList = dbContext.Customers.Include("CustomerManager");
刚学EF,不懂要Include,查到的记录CustomerManager都是null,Include之后才有数据,在此标志一下
EF外键关联
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。