如何使用实体框架代码优先方法

我正在使用EF代码优先方法的项目中工作。我是新来的。

我几乎不怀疑有人是否可以帮助我:

  1. How to set an identity column
  2. How to set a foreign key
  3. Can we insert some dummy record while creating a table using model builder?

  4. Can we set identity column and foreign key using model builder only or do we need to set these in model class as well?

  5. Can we add extra property in model class irrespective of model builder(just in case we need to fetch result from a procedure and need to add some other property)?

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("Relational:DefaultSchema", "dbo");
            modelBuilder.Entity<TblCountry>(entity =>
            {
                entity.HasKey(e => e.CountryId);
    
                entity.ToTable("tbl_Countries", "dbo");
    
                entity.Property(e => e.CountryId).HasColumnName("CountryId");
                entity.Property(e => e.CountryId).HasDatabaseGeneratedOption
                entity.Property(e => e.CountryName)
                    .IsRequired()
                    .HasMaxLength(120)
                    .IsUnicode(false);
            entity.Property(e => e.Status).HasMaxLength(1).HasDefaultValue(1);
            });
    
            modelBuilder.Entity<TblState>(entity =>
            {
                entity.HasKey(e => e.StateId);
    
                entity.ToTable("tbl_States", "dbo");
    
                entity.Property(e => e.StateId).HasColumnName("StateID");
    
                entity.Property(e => e.StateName)
                    .IsRequired()
                    .HasMaxLength(120)
                    .IsUnicode(false);
                entity.Property(e => e.Status).HasMaxLength(1).HasDefaultValue(1);
            });
        } 
    
    public partial class TblCountry
    {
        //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }
    
    public partial class TblState
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public int CountryId { get; set; }
    }
    
评论