EF Fluent映射DbGeography报错:求非空值类型问题解决方案
Hey, I’ve run into this exact error before when working with EF Fluent mappings and spatial types like DbGeography, so let me break down what’s going on and the fixes that worked for me.
The Root Cause
The error happens because System.Data.Spatial.DbGeography is a reference type (a class), but some of EF’s generic mapping methods have constraints expecting a non-nullable value type (struct). When you call .IsRequired() on the generic Property<T> overload for a reference type, EF’s internal type checking throws this error.
Working Solutions
Use the Non-Generic
PropertyMethod
Avoid the generic constraint issue entirely by using the non-generic overload that takes a property name string. Explicitly set the column type togeographyto ensure EF recognizes it as a spatial type:this.Property("Location") .HasColumnType("geography") .IsRequired();Ensure Proper Spatial Type Configuration
If you prefer the generic method, first make sure EF is set up to handle spatial types correctly. Add this configuration at the start of yourOnModelCreatingmethod to set a default coordinate system (most commonly WGS84, used by GPS):protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Set default coordinate system (WGS84) System.Data.Entity.Spatial.DbGeography.DefaultCoordinateSystemId = 4326; // Now map your property with the generic method modelBuilder.Entity<YourEntity>() .Property(e => e.Location) .HasColumnType("geography") .IsRequired(); }Verify Your Entity Type Definition
Double-check that yourGeographyalias points to the correct reference type (not a custom value type). Your entity should look like this:// Alias for clarity (optional but recommended) using Geography = System.Data.Entity.Spatial.DbGeography; public class YourEntity { public int Id { get; set; } // DbGeography is a reference type, no need for nullable syntax public Geography Location { get; set; } }Update Entity Framework
If you’re using an older version of EF (like EF5 or earlier), spatial type support is limited. Upgrade to EF 6.1.3 or later—these versions have better handling forDbGeographyin Fluent mappings.
Give these steps a try—this resolved the exact error message you’re seeing for me when working with spatial data in EF.
内容的提问来源于stack exchange,提问作者Krzysztof Tryc

