首页 新闻 赞助 找找看

ef code first生成数据库错误

0
悬赏园豆:10 [已解决问题] 解决于 2014-03-03 11:51

模型生成过程中检测到一个或多个验证错误:

OMS.Repository.Context.Customer_BelongTo: : 多重性与关系“Customer_BelongTo”中 Role“Customer_BelongTo_Target”中的引用约束冲突。因为 Dependent Role 中的所有属性都不可以为 null,Principal Role 的多重性必须为“1”。

这个是什么原因,怎么解决?

 

public class Customer : BaseEntity
    {
        public string Code { get; set; }

        public string Name { get; set; }

        public int RankId { get; set; }

        //其他属性略

        /// <summary>
        /// 归属人,可以为空
        /// </summary>
        public Login BelongTo { get; set; }

        public int BelongToUserId { get; set; }
    }
    public class Login : BaseEntity, IPrincipal
    {
        public Login()
        {
            Roles = new List<Role>();
        }

        public string UserName { get; set; }

        public string Email { get; set; }

        public string Password { get; set; }

        public bool Enabled { get; set; }

        public virtual User UserInfo { get; set; }

        public virtual ICollection<Role> Roles { get; set; }

        public IIdentity Identity
        {
            get
            {
                var isAuthenticated = Id > 0;
                return new Identity(isAuthenticated, UserName);
            }
        }

        public bool IsInRole(string role)
        {
            return false;
        }

        public virtual Organization Organization { get; set; }

        /// <summary>
        /// 全部权限
        /// </summary>
        public IList<UnitPermission> UnitPermissions
        {
            get
            {
                var permissions = new List<UnitPermission>();
                foreach (var role in Roles.Where(f => f.Enabled))
                {
                    permissions.AddRange(role.UnitPermissions);
                }

                return permissions.Distinct().ToList();
            }
        }
    }
 public class CustomerCinfig : EntityMapperBase<Customer>
    {
        public CustomerCinfig()
        {
            HasKey(f => f.Id);
            Property(f => f.Code).HasMaxLength(20).IsRequired();
            Property(f => f.Name).HasMaxLength(40).IsRequired();
            HasRequired(f => f.Rank).WithMany().HasForeignKey(f => f.RankId).WillCascadeOnDelete(false);
            HasOptional(f => f.BelongTo).WithMany().HasForeignKey(f => f.BelongToUserId);
        }
    }
Kratos Zhang的主页 Kratos Zhang | 初学一级 | 园豆:6
提问于:2014-03-03 11:35
< >
分享
最佳答案
0

HasOptional(f => f.BelongTo). 改成 HasRequired

收获园豆:10
Launcher | 高人七级 |园豆:45045 | 2014-03-03 11:44

但是这个字段并不是必填项额

Kratos Zhang | 园豆:6 (初学一级) | 2014-03-03 11:46

貌似是 public int BelongToUserId { get; set; } 的问题

改成 public int? BelongToUserId { get; set; } 就好了。。。  冏

Kratos Zhang | 园豆:6 (初学一级) | 2014-03-03 11:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册