【问题标题】:Ignore Propertyname in EF6 Insert忽略 EF6 插入中的属性名
【发布时间】:2021-02-01 14:17:01
【问题描述】:

我正在使用 EF6 使用数据库优先方法将记录插入 sql 数据库。 我在 sql 表中有一个名为 AccountNumber 的计算字段,因此在调用 context.Savechanges() 后,我收到了一个实体验证错误事件,尽管我没有将任何值传递给模型 comps 中的该属性。插入时如何忽略 AccountNumber 属性

using (PMMCEntities context = new PMMCEntities())
                    {
                        var comps = new RHEMA_CLIENTS()
                        {
                            //AccountNumber ="",// Convert.ToInt32(Request.Form["accno"]),
                            CompanyName = Request.Form["Company"],
                            Location = Request.Form["location"],
                            Address = Request.Form["address"],
                            Telephone1 = Request.Form["tel1"],
                            Telephone2 = Request.Form["tel2"],
                            Email1 = Request.Form["email1"],
                            Email2 = Request.Form["email2"],
                            Website = Request.Form["website"],
                            ContactName = Request.Form["contactname"],
                            ContactPosition = Request.Form["contactname"],
                            ContactPhone = Request.Form["contactphone"],
                            ContactEmail = Request.Form["contactemail"],
                            BusinessRegNo = Request.Form["regno"],
                            TIN = Request.Form["TIN"],
                            LicenseNo = Request.Form["license"],
                            LicenseExpiryDate = Convert.ToDateTime(exp,CultureInfo.InvariantCulture),
                            EntityType = Request.Form["entity"],
                            CapitalStructure = Request.Form["capital"],
                            CustomerCategory = Request.Form["category"],
                            CreatedDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture),
                            Frozen = frozen
                        };

                        context.RHEMA_CLIENTS.Add(comps);
                        context.SaveChanges();

【问题讨论】:

  • 您使用 EDMX 文件吗?
  • 是的,我使用的是 EDMX 文件

标签: c# sql-server entity-framework


【解决方案1】:

您的 AccountNumber 属性上方的[NotMapped] 属性 如下,

[NotMapped]
public <Type> <Name>{get; set; }

这可能对 DB First 有所帮助 https://entityframework.net/knowledge-base/38445897/how-to-exclude-certain-columns-in-ef6-using-database-first-

【讨论】:

  • 谢谢,但由于这是数据库优先的方法,重新生成代码时任何更改都将被覆盖
  • 您可能需要从数据库中更新模型,然后从模型类中手动删除此属性
  • 谢谢,但是在 GET 方法中需要同样的属性来检索数据库中的值以进行显示
  • 模型类更新后,也应该可以正常检索了
【解决方案2】:

您可以在实体类中使用 [NotMapped] 属性来装饰属性。

【讨论】:

  • 谢谢,但由于这是数据库优先的方法,重新生成代码时任何更改都将被覆盖
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多