即使在DB中持久存在,也未映射EF原始属性

时间:2014-03-24 13:30:38

标签: c# sql-server database entity-framework dbcontext

我有以下课程:

 public class MyModel
    {
        public Guid Id { get; set; }
        public DateTime Timestamp { get; set; }
        public string Address { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string State { get; set; } 
    }

以及以下上下文:

public class ApplicationDbContext : DbContext<MyModel>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        public virtual DbSet<MyModel> MyModels { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<MyModel>().ToTable("MyModels");
        }
    }

当我保存在数据库中时,我只分配了一些字段Timestamp,Address,Name以及我稍后更新它们的其余字段(City,State):

var model = new MyModel(){Timestamp = DateTime.Now, Address = "value here", Name = "value here"};
_dbContext.MyModels.Add(model);
_dbContext.SaveChanges(); => Everything is persisted fine in DB

....稍后......

var model = _dbContext.MyModels.Where(...);
model.State = "Value here"; //And the rest of the properties updated here
_dbContext.SaveChanges(); => Everything is updated fine in DB 

....甚至更晚

var model = _dbContext.MyModels.Where(...);

=&GT;这里只检测首先初始化的属性(时间戳,地址,名称),而更新的属性(城市,州)为空,即使在DB中具有正确的值。

我究竟做错了什么?

编辑:

如果我重新初始化_dbContext

_dbContext = new ApplicationContext()
var model = _dbContext.MyModels.Where(...); 

在查询集合之前的最后一个代码片段中,我得到了正确的结果。为什么会这样?

0 个答案:

没有答案