简体   繁体   中英

Not able to use Nullable DbGeography

I have a geography field in SQL which I marked as null.

Then on my EF Entity I added a nullable DbGeography? property but I get a message saying that is not allowed.

So, how can I insert in the database a DbGeography that is not defined?

I was looking for something like DbGeography.Empty or DbGeography.Unknown.

But I wasn't able to find any ...

Thank You, Miguel

DbGeography is a class so it is already nullable. Just give it a null value in your model.

If you want a non-null-able DbGeography property, but wanted to express an empty (but not null) value, you could do this...

[Required] public virtual DbGeography GpsCoordsOrWhatever { get; set; } = DbGeography.FromText("POINT EMPTY")

DbGeography and the other types in the System.Data.Entity.Spatial namespace are classes (reference types and therefore null-able).

Conversely, if you wanted to have a non-null-able property of class-type you would apply the [Required] attribute to the property, or use modelBuilder.Entity<Entity>().Property(t => t.Property).IsRequired() . This doesn't prevent null assignment to the property, but it will be mapped to a non-null-able field in the backing store (database in most cases) and will be checked for null in Entity Framework's validation.

This is because DbGeography is class and it is not allowed to have mark classes as nullable (the nullable thing is only for structures).

Change type of your property to DbGeography (not DbGeography? ). As DbGeography is class it is ok for property to have null value.

Entities don't need to be explicitly marked as nullable. You will be able to set it to null anyway.

You would able to do MyDbGeographyProperty = null; Latitude and Longitude is read-only from the obj Which is what kjbartel stated;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM