如何在我的Entity框架上关闭自动生成?

时间:2014-04-10 08:30:04

标签: entity-framework

我使用了EF codefirst。我的域名模型如下:

public class Book
{
    public Book()
    {
        BookType = new BookType();
        BookPlace = new BookPlace();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public string Publishment { get; set; }
    public int BookTypeID { get; set; }
    public int BookPlaceID { get; set; }

    public BookType BookType { get; set; }
    public BookPlace BookPlace { get; set; }
}

public class BookType
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class BookPlace
{
    public int ID { get; set; }
    public string Position { get; set; }
}

这是我的doamin mapper:

public class BookMapper:EntityTypeConfiguration<Book>
{
    public BookMapper()
    {
        this.ToTable("Book");

        this.HasKey(c => c.ID);
        this.Property(c => c.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Property(c => c.ID).IsRequired();

        this.Property(c => c.Name).HasMaxLength(255);
        this.Property(c => c.Name).IsRequired();

        this.Property(c => c.Author).HasMaxLength(255);
        this.Property(c => c.Author).IsOptional();

        this.Property(c => c.Publishment).HasMaxLength(255);
        this.Property(c => c.Publishment).IsRequired();

        this.HasRequired(c => c.BookType).WithMany().HasForeignKey(s => s.BookTypeID).WillCascadeOnDelete(false);
        this.HasRequired(c => c.BookPlace).WithMany().HasForeignKey(s => s.BookPlaceID).WillCascadeOnDelete(false);

    }
}

public class BookTypeMapper : EntityTypeConfiguration<BookType>
{
    public BookTypeMapper()
    {
        this.ToTable("BookType");

        this.HasKey(c => c.ID);
        this.Property(c => c.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Property(c => c.ID).IsRequired();

        this.Property(c => c.Name).IsRequired();
        this.Property(c => c.Name).HasMaxLength(255);
    }
}

public class BookPlaceMapper : EntityTypeConfiguration<BookPlace>
{
    public BookPlaceMapper()
    {
        this.ToTable("BookPlace");

        this.HasKey(c=>c.ID);
        this.Property(c => c.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Property(c => c.ID).IsRequired();

        this.Property(c => c.Position).IsRequired();
        this.Property(c => c.Position).HasMaxLength(255);
    }
}

这是我的BookContext:

public class BookContext : DbContext, IDbContext
{
    public BookContext()
        : base("BookConnection")
    {
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookContext, BookContextMConfig>());
    }

    public DbSet<Book> Books { get; set; }
    public DbSet<BookType> BookTypes { get; set; }
    public DbSet<BookPlace> BookPlaces { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new BookMapper());
        modelBuilder.Configurations.Add(new BookTypeMapper());
        modelBuilder.Configurations.Add(new BookPlaceMapper());
        base.OnModelCreating(modelBuilder);
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }
}

这是我的IRepository接口和Repository类:

public interface IRepository<T> where T:class
{
    T GetByID(long id);
    T GetByID(int id);
    T GetByID(Guid id);
    T GetByID(string id);
    T Get(Expression<Func<T, bool>> where);
    IQueryable<T> GetMany(Expression<Func<T, bool>> where);

    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
    void Delete(Expression<Func<T, bool>> where);
}

public class Repository<T>:IRepository<T> where T:class
{
    public Repository(IDbContext context)
    {
        this.context = context;
    }

    private IDbContext context;

    private IDbSet<T> dbset;
    public virtual IDbSet<T> DbSet
    {
        get
        {
            if (dbset == null)
                dbset = context.Set<T>();
            return dbset;
        }
    }

    ...   

    public virtual void Insert(T entity)
    {
        try
        {
            if (entity == null)
                throw new ArgumentException("实体类为空");
            DbSet.Add(entity);
            context.SaveChanges();
        }
        catch (DbEntityValidationException dbex)
        {
            var msg = string.Empty;
            foreach(var validationErrors in dbex.EntityValidationErrors)
                foreach(var validateionError in validationErrors.ValidationErrors)
                    msg+=string.Format("Property:{0} Error:{1}",validateionError.PropertyName,validateionError.ErrorMessage);

            var fail = new Exception(msg,dbex);
            throw fail;
        }
    }
}

现在的问题是:每当我尝试将书籍数据添加到数据库时,Repository.cs类中的Insert方法都会引发异常,因为:BookPlace表中的位置值是必需的。 BookType表中的名称值是必需的。

我不知道为什么导致这种情况,有人会给我一些建议吗? THX。

1 个答案:

答案 0 :(得分:0)

我终于通过以下方式解决了这个问题:

更改书籍模型如下:

public class Book
{

public int ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string Publishment { get; set; }
public int BookTypeID { get; set; }
public int BookPlaceID { get; set; }

public virtual BookType BookType { get; set; }
public virtual BookPlace BookPlace { get; set; }
}