0

I'm working with Entity Framework code first. The error occurs when trying to save a negative decimal value into the SQL Server database. The model that I'm trying to save is listed below.

public class Material
{
        public Material()
        {
            Categories = new List<Category>();
        }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        [Required]
        public string Name { get; set; }
        public string Description { get; set; }
        [Required]
        public DateTime Taken { get; set; }
        public decimal? Latitude { get; set; }
        public decimal? Longitude { get; set; }
        public virtual ICollection<Category> Categories { get; set; }
    }

Here I'm trying to set the precision of the decimal (Latitude/Longitude) in the model Material.

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
        modelBuilder.Entity<Material>().Property(x => x.Latitude).HasPrecision(8, 7);
        modelBuilder.Entity<Material>().Property(x => x.Longitude).HasPrecision(8, 7);
 }

In the database the column information looks like this:

dbo.Materials.Latitude (decimal(8, 6), null)

dbo.Materials.Longitude (decimal(8, 6), null)

If I try to save a negative value like -1m everything works fine. But as soon is I try to save any bigger value or value with decimals like -123 or -123.123456 the data context always throws an exception when saving.

The exception I'm getting is this:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Looking in to the inner exception we can see that this might be the cause of the problem:

{"Parameter value '-117.246108' is out of range."}

How can I solve this problem ?

4

2 に答える 2

2

私の知る限り、拡張子「HasPrecision(8, 7)」で、10 進数を合計 8 桁に定義しています。右側は最大 7 桁です。10 進数の -117.246108 は 9 桁です。"HasPrecision(9, 7)" を変更してみてください。

于 2012-04-10T10:55:26.010 に答える
1

モデルを構成したとおりに動作します。HasPrecision(8,7)は、小数点の両側で許容される合計桁数が 8 であり、小数点の右側の合計桁数が 7 であることを意味します。したがって、小数点の左側には 1 桁のみを含めることができます。「-117.246108」を格納するには、少なくとも精度 9 と位取り 6 が必要です。

于 2012-04-10T10:55:37.853 に答える