RIA/EF4 Entity property mapped to NOT NULL nvarchar - empty string

爷,独闯天下 提交于 2019-12-21 09:22:12

问题


Background:

  • Entity Framework 4
  • Silverlight 4
  • RIA services
  • MSSQL Server 2008

I have an entity that has a String property named Description.

In database it maps to the NOT NULL NVARCHAR(200).

Problem:

When I try to insert a new row of that entity, this is what I do:

MyExampleEntity entity = new MyExampleEntity()
{
    Name = "example",
    Description = ""        // NOTE THIS LINE!
};

DatabaseContext db = new DatabaseContext();
db.MyExampleEntities.Add(entity);
db.SubmitChanges();

This, however, causes an exception saying "The Description field is required."

Question:

Should not the "empty string" be simply that - a string with zero characters?

I believe only Description = null should be treated as providing no value.

  • Why is my string, which has a value (although its length is 0), considered to be as if I have omitted the value?
  • On what level does this conversion happen? On RIA, on EF or in MSSQL?
  • Is there a way to make a description have zero-length value when I set the Description to "" and cause an exception when Description = null (having no value)?

回答1:


This appears to be a symptom of Entity Framework.

Related Article

Some data annotations can be used to overcome this:

[MetadataType(typeof(Report_META))]
   public partial class Report
   {
   }

   public partial class Report_META
   {
       [Required(AllowEmptyStrings = true)]
       [DisplayFormat(ConvertEmptyStringToNull = false)]
       public object Note { get; set; } 
    }


来源:https://stackoverflow.com/questions/6548304/ria-ef4-entity-property-mapped-to-not-null-nvarchar-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!