简体   繁体   English

C# Entity Framework 6 Code First:如何为存储在 DB 中的属性定义特定的 setter

[英]C# Entity Framework 6 Code First: how to define a specific setter for a property stored in DB

I'm using Entity Framework 6 Code First and would to update a value before saved in it DB.我使用的是Entity Framework 6 Code First,并会在保存到数据库之前更新一个值。 I have a model with properties mapped to db table fields and for one of them, MyBackField , I want to trim his value before saving the entity in db via SaveChanges().我有一个 model 的属性映射到 db 表字段,对于其中一个MyBackField ,我想在通过 SaveChanges() 将实体保存在 db 中之前修剪他的值。 I tried to use backing fields like that:我尝试使用这样的支持字段:

private string MyBackField;
public string MyFrontField{ get => MyBackField; set => MyBackField = value?.Trim(); }

The thing is: field MyBackField exists already in db, when I change it from public to private property, the Update-Database command generates a migration file to drop it from db.问题是:字段MyBackField已经存在于数据库中,当我将其从公共属性更改为私有属性时,Update-Database 命令会生成一个迁移文件以将其从数据库中删除。

How can I do this?我怎样才能做到这一点?

Finally I switched the member and the property and it worked perfectly.最后我切换了成员和属性,它工作得很好。

Thks @GertArnold谢谢@GertArnold

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过实体框架代码优先方法定义导航属性 - How to define a navigation property via Entity Framework code first approach 首先使用实体​​框架代码-如何定义自定义导航属性 - Entity Framework code first - How to define a custom navigation property 如何在 C#/实体框架中的 NotMapped 属性的 setter 中使用映射属性 - How can I use a mapped property in the setter of a NotMapped property in C# / Entity Framework 实体框架DB首先 - 私有setter - Entity framework DB first - private setter 实体框架代码首先,非空的setter或getter? - Entity Framework Code First, nonempty setter or getter? Entity Framework Core DB先行,如何在不同的C#核心项目中添加实体关联 - Entity Framework Core DB first, How to add an entity association in different C# core projects 将列添加到 C# 和实体框架代码中的表中,而不删除数据库内容 - Add column to table in C# & Entity Framework code-first without deleting DB content C#自定义设置器实体框架6.1.3 - C# Custom Setter Entity Framework 6.1.3 代码优先实体框架C#,多对多映射,创建连接表,但未在对象上填充列表属性 - Code First Entity Framework C#, Many to Many Mapping, Junction Table Created but list property not populated on object C#实体框架-代码优先-数据对象属性解析为空 - C# Entity Framework - Code First - Data Object Property Resolves Null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM