简体   繁体   English

无法使用Nullable DbGeography

[英]Not able to use Nullable DbGeography

I have a geography field in SQL which I marked as null. 我在SQL中有一个地理字段,我将其标记为null。

Then on my EF Entity I added a nullable DbGeography? 然后在我的EF实体上我添加了一个可以为空的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? 那么,如何在数据库中插入未定义的DbGeography?

I was looking for something like DbGeography.Empty or DbGeography.Unknown. 我正在寻找像DbGeography.Empty或DbGeography.Unknown这样的东西。

But I wasn't able to find any ... 但是我找不到任何......

Thank You, Miguel 谢谢你,米格尔

DbGeography is a class so it is already nullable. DbGeography是一个类,所以它已经可以为空了。 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... 如果你想要一个非null的DbGeography属性,但想表达一个空(但不是null)的值,你可以这样做......

[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). DbGeographySystem.Data.Entity.Spatial命名空间中的其他类型是类(引用类型,因此可以为null)。

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() . 相反,如果你想拥有class-type的非null modelBuilder.Entity<Entity>().Property(t => t.Property).IsRequired()属性,你可以将[Required]属性应用于属性,或者使用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. 这不会阻止对属性的null赋值,但它将映射到后备存储中的非null -able字段(大多数情况下为数据库),并且将在Entity Framework的验证中检查null

This is because DbGeography is class and it is not allowed to have mark classes as nullable (the nullable thing is only for structures). 这是因为DbGeography是类,并且不允许将标记类作为nullable (可以为nullable东西仅用于结构)。

Change type of your property to DbGeography (not DbGeography? ). 将您的房产类型更改为DbGeography (而不是DbGeography? )。 As DbGeography is class it is ok for property to have null value. 由于DbGeography是类,因此属性可以具有null值。

Entities don't need to be explicitly marked as nullable. 实体不需要明确标记为可为空。 You will be able to set it to null anyway. 无论如何,您将能够将其设置为null。

You would able to do MyDbGeographyProperty = null; 你可以做MyDbGeographyProperty = null; Latitude and Longitude is read-only from the obj Which is what kjbartel stated; 纬度和经度是从obj只读的,这是kjbartel所说的;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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