代码优先模型定义

时间:2014-04-17 13:25:36

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 ef-code-first

我有以下型号,我定义好吗?

  1. 用户是主要实体,可以有0..1到*(零/一对多关系)地址。
  2. 2.User可以有0..1到1(一对一userPass)

    这是主表

    public class User
    {
    
        [Key]
        [Required]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email    { get; set; }
        public string Phone { get; set; }
        public string PhoneWork { get; set; }
        public string WorkingAt { get; set; }
    
        public virtual UserPass UserPass { get; set; }
    
        public virtual ICollection<Address> Addresses { get; set; }
    }
    
    public class ConfigModelDbContext : DbContext
    {
        public DbSet<User> User { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<UserPass> UserPasses { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    
            modelBuilder.Entity<User>()
                .HasOptional(c => c.Addresses).WithRequired(addresses => new User());
    
            modelBuilder.Entity<User>()
                .HasOptional(c => c.UserPass).WithRequired(pass => new User());
    
        }
    }
    

    地址类

    public class Address
    {
        [Key]
        [ForeignKey("User")]
        public string UserId { get; set; }
        public string UserAddress { get; set; }
    }
    

    Userpass类

    public class UserPass
    {
        [Key]
        [ForeignKey("User")]
        public string UserId { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
    }
    

    我还创建了与上面相同的类,但是它可以直接在数据库表上创建关系吗?

1 个答案:

答案 0 :(得分:1)

起初我总是让你使用数据注释而不是流畅的api。

然后更正如下所示的AddressClass:

public class Address
        {
            [Key]
            public int Id { get; set; }
            [ForeignKey("UserId")]
            public User User { get; set; }
            public string UserId { get; set; }
            public string UserAddress { get; set; }
        }

这将创建Ralationship。 有关详细信息,请阅读Code First DataAnnotations