忽略更新实体框架上的一个属性 [英] Ignore one property on update Entity Framework

查看:61
本文介绍了忽略更新实体框架上的一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET C#和Entity Framework。

I'm working with .NET C# and Entity Framework.

我有一种情况需要更新数据库中的对象,但我会保留一个属性保持不变。我想知道是否可以这样做?

I have a situation where I need to update an object in the database but I'll keep one property untouched. I'd like to know is it possible to do that?

以下面的类为例:

public class Person
{
    public int PersonId { get; set; }
    public string Name{ get; set; }
    public int Age { get; set; }
    public DateTime CreationDate { get; set; }
}

因此,我将在页面中提供HTML表单供客户端进行编辑一个人。
示例:

So I would provide a HTML form in a page for the client to edit a person. Example:

<form>
    <input type="hidden" id="PersonId" value="1" />
    <input type="text" id="Name" value="Cesar" />
    <input type="text" id="Age " value="28" />
</form>

然后我抓住值并将其发送到存储库以更新该Person。但这对更新CreationDate没有意义,我不想提供这种可能性。

Then I'd grab the values and send to the repository to update that Person. But it does not make sense updating CreationDate, and I don't want to provide that possibility.

所以我可以用两种不同的方式来实现。

So I could do it in 2 different ways.

1)我可以将其放在表单中作为隐藏字段并将其发布回去。 (但正如我说的那样,我不想提供这种可能性)。

1) I could put it in the form as a hidden field and post it back. (but as I said I don't want to provide that possibility)

2)在存储库中,获取Person,更新其字段,并保持CreationDate日期不变,然后保存它:

2) In the repository get the Person, update it's fields and leave CreationDate date the same and then save it:

void UpdatePerson(Person p){
    var person = db.Persons.Find(PersonId);

    person.Name = p.Name;
    person.Age = p.Age;

    db.Persons.Attach(person);
    db.Entry(person).State = EntityState.Modified;
    db.SaveChanges();        
}

我想知道我可以通过 p的方法

I'd like to know a way that I could just pass "p" to the context and update it leaving CreationDate the way it is.

我希望我更清楚。

我非常抱歉第一篇文章中的信息不足。

I'm sorry about the lack of information in the first post.

感谢您的帮助。

推荐答案

我个人使用AutoMapper并在不想复制的一个字段上使用忽略。这样,如果您将新列添加到表中,就不必担心将它们添加到存储库中。

Personally, I use AutoMapper and use Ignore on the one field you don't want to copy. This way, if you ever add new columns to the table, you don't have to worry about adding them to your repository.

所以,像这样...

void UpdatePerson(Person p) {
    var person = db.Persons.Find(PersonId);

    Mapper.CreateMap<Person, Person>()
        .ForMember(dest => dest.CreationDate, opt => opt.Ignore());
    Mapper.Map(p, person);        

    db.SaveChanges();        
}

这篇关于忽略更新实体框架上的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆