【问题标题】:Update just one field in Entity Framework 6仅更新 Entity Framework 6 中的一个字段
【发布时间】:2014-09-08 16:56:12
【问题描述】:

我已经尝试过本教程,但它对我不起作用 (Link),我的目标是只更新我的实体的一个字段...没有其他字段。我正在测试 EntityFramework,我想检查是否可以在仅更新一个字段后执行 DTO 的自动映射器。

我试过这个:

MyContext db = new MyContext();
MyClass sampleModel = new MyClass();
sampleModel.IdMyClass = "1d1ba1f2-8c08-c334-5486-08d16fecc6e3"; //GUID
sampleModel.ModificationDate = DateTime.Now;
db.MyClass.Attach(sampleModel);
db.Entry(sampleModel).Property(x => x.ModificationDate).IsModified = true;
db.SaveChanges();

MyClass 类

public partial class MyClass 
{
    public string IdMyClass { get; set; }
    public string Name { get; set; }        
    public System.DateTime ModificationDate { get; set; }
    public virtual ICollection<OtherClass> OtherClass{ get; set; }        
}

MyClassMap

public MyClassMap() : EntityTypeConfiguration<MyClass>
{
    //Primary Key
    this.HasKey(t => t.IdMyClass);
    //Properties
    this.Property(t => t.Name)
        .IsRequired()
        .HasMaxLength(256);

    // Table & Column Mappings
    this.ToTable("MyClass");
    this.Property(t => t.IdMyClass).HasColumnName("IdMyClass");
    this.Property(t => t.Name).HasColumnName("Name");
    this.Property(t => t.ModificationDate).HasColumnName("ModificationDate");            
}

我的问题在哪里??

错误详情,发生在 db.SaveChanges()

类型异常 'System.Data.Entity.Validation.DbEntityValidationException' 发生 在 EntityFramework.dll 中,但未在用户代码中处理

附加信息:一个或多个实体的验证失败。 有关详细信息,请参阅“EntityValidationErrors”属性。

EntityValidationErrors 为空...

【问题讨论】:

  • 您能否详细说明您的代码“不起作用”的原因?你期待什么,实际发生了什么?如果您遇到异常,请发布发生异常的行和异常详细信息。
  • 我认为,Name = null on db.SaveChanges();
  • 您可以附加一个实体,而无需从数据库中请求它。
  • @Rodrigo - 是的,你说得对。
  • 不,对不起,不要听我的。 @Rodrigo 是对的。你可以像你正在做的那样附加它。只需在附加之前指定名称。

标签: c# entity-framework asp.net-mvc-5


【解决方案1】:

您可以使用以下内容定义哪些属性将被更新:

MyContext db = new MyContext();
MyClass sampleModel = new MyClass();
sampleModel.IdMyClass = "1d1ba1f2-8c08-c334-5486-08d16fecc6e3"; //GUID
sampleModel.ModificationDate = DateTime.Now;
sampleModel.Name=string.Empty; //should not be needed
db.MyClass.Attach(sampleModel);
var entry=db.Entry(sampleModel);
entry.State = EntityState.Modified;
var excluded = new string[] { "Name" };
foreach (var name in excluded)
{
   entry.Property(name).IsModified = false;
}
db.SaveChanges();

好的,这是我的代码版本。 课程

public partial class MyClass
{
    public string IdMyClass { get; set; }
    public string Name { get; set; }
    public System.DateTime ModificationDate { get; set; }
    public ICollection<OtherClass> OtherClass { get; set; }
}
public partial class OtherClass
{
    public int Id { get; set; }
    public string Stuff { get; set; }
}

public class MyContext : DbContext
{
    public MyContext()
        : base("MyContextDb")
    {

    }
    public DbSet<MyClass> MyClasses { get; set; }
    public DbSet<OtherClass> OtherClasses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyClass>().ToTable("MyClass");
        modelBuilder.Entity<MyClass>()
            .HasKey(t => t.IdMyClass)
            .Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(256);
        modelBuilder.Entity<MyClass>().Property(t => t.IdMyClass).HasColumnName("IdMyClass");
        modelBuilder.Entity<MyClass>().Property(t => t.Name).HasColumnName("Name");
        modelBuilder.Entity<MyClass>().Property(t => t.ModificationDate).HasColumnName("ModificationDate");

    }
}  

一个简单的控制台程序来测试结果

class Program
{
    static void Main(string[] args)
    {
        MyContext db = null; ;
        try
        {
            db = new MyContext();
            Foo(db);
            Console.WriteLine("Id\tDate\tName");
            foreach(var c in db.MyClasses)
            {
                Console.WriteLine("{0}\t{1}\t{2}",c.IdMyClass,c.ModificationDate,c.Name);
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (db != null)
            {
                db.Dispose();
            }
        }
        Console.ReadLine();

    }

    static void Foo(MyContext db)
    {
        var sampleModel = new MyClass();
        sampleModel.IdMyClass = "1d1ba1f2-8c08-c334-5486-08d16fecc6e3"; //GUID
        sampleModel.ModificationDate = DateTime.Now;
        sampleModel.Name = string.Empty; //should not be needed
        db.MyClasses.Attach(sampleModel);
        var entry = db.Entry(sampleModel);
        entry.State = EntityState.Modified;
        var excluded = new string[] { "Name" };
        foreach (var name in excluded)
        {
            entry.Property(name).IsModified = false;
        }
        db.SaveChanges();
    }
}

希望对您有所帮助。

【讨论】:

  • EntityFramework.dll 中出现“System.Data.Entity.Validation.DbEntityValidationException”类型的异常,但未在用户代码中处理其他信息:一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。
  • 好的,我稍后再测试,我在家...但是我认为它是如此复杂...我想在具有很多 DTO 的 API REST 中使用...谢谢这么多,如果它的工作,我会投票给你的答案好;)
  • 好的,可以,但是 sampleModel.Name=string.Empty; //不应该是需要的,是需要的! :(我不知道为什么...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
相关资源
最近更新 更多