CodeFirst第一天学习遇到问题请教大佬们 返回

SqlSugar 处理完成
5 111
该叫什么 →_→ 发布于2周前
悬赏:0 飞吻

用sqlsugar的codefirst创建数据库时,如何设置实体映射阿,创建的表在数据库中没有关系,还需要写什么吗

public class User

    {

        [SugarColumn(IsPrimaryKey =true,IsIdentity =true)]

        public int id { get; set; }

        public string? UserName { get; set; }

        public string? Password { get; set; }

        public string? phone { get; set; }

        public string? ShengFenZH { get; set; }

        //[Navigate(typeof(UserRole),nameof(UserRole.UserId),nameof(UserRole.RoleId))]

        [SugarColumn(IsIgnore =true)]

        public List<UserRole>? userRoles { get; set; } = new List<UserRole>();

    }

public class Role

    {

        [SugarColumn(IsPrimaryKey =true,IsIdentity =true)]

        public int id { get; set; }

        public string? RoleName { get; set; }

        //[Navigate(typeof(UserRole),nameof(UserRole.RoleId),nameof(UserRole.UserId))]

        [SugarColumn(IsIgnore = true)]

        public List<UserRole>? userRoles { get; set; } = new List<UserRole>();

        //[Navigate(typeof(RoleMenuInfo),nameof(RoleMenuInfo.roleId),nameof(RoleMenuInfo.menuInfoId))]

        [SugarColumn(IsIgnore = true)]

        public List<RoleMenuInfo>? roleMenuInfos { get; set; } = new List<RoleMenuInfo>();

    }

 public class UserRole

    {

        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] // 定义主键

        public int Id { get; set; }

        //public int id { get; set; }

        //[SugarColumn(IsPrimaryKey =true)]

        public int? UserId { get; set; }

        //public User User { get; set; }

        //[SugarColumn(IsPrimaryKey = true)]

        public int? RoleId { get; set; }

        //public Role Role { get; set; }

    }

public void CreateDb()

        {

            using (SqlSugarClient db = new SqlSugarClient(ConnectionConfig))

            {

                db.DbMaintenance.CreateDatabase();

                Type[] types = Assembly

                    .LoadFrom(@"E:\animal\DEMO\DEMO\bin\Debug\netcoreapp3.1\DEMO.Mode.dll")

                    .GetTypes().Where(t => t.IsClass && !t.IsAbstract && !t.FullName.Contains("Lay"))

                    .ToArray();

                db.CodeFirst.InitTables(types);

                

                

            }

        }


热忱回答5

  •     //[Navigate(typeof(UserRole),nameof(UserRole.UserId),nameof(UserRole.RoleId))]

            [SugarColumn(IsIgnore =true)]

            public List<UserRole>? userRoles { get; set; } = new List<UserRole>();


    改成


        [Navigate(typeof(UserRole),nameof(UserRole.UserId),nameof(UserRole.RoleId))]

            public List<UserRole>? userRoles { get; set; } ;



    0 回复
  •  不能有默认值 ,sqlsugar不依赖主外键关系就能查询,所以只配置正确就好

    0 回复
  • @fate sta:大佬,就是在sqlserver里面查看关系是这样的,没有关系连线,sqlsugar创建表是这样的吗?image.png

    0 回复
  • @→_→:sqlsugar不需要关系就能导航操作,也就是只需要在实体里面配置导航,而不用生成数据库关系。

    0 回复
  • @fate sta:好的,感谢大佬


    0 回复