[英]Entity Framework Non-nullable column is mapped to a nullable entity property
[英]Get the 'Nullable' state programmatically of a Property in Entity Framework
我需要獲取EF中的字段的Nullable屬性。 需要對Nullable = True的屬性執行一些魔術代碼,但我找不到有效的解決方案來刪除該屬性。
foreach (PropertyInfo property in (PropertyInfo[])type.GetProperties())
{
var getPropertyType = property.GetMethod.ReturnTypeCustomAttributes.ToString();
var getValue = property.GetValue(model);
bool isNullable = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
// isNullable always returns false !!!! and I need it to return true if the field is allowed to be null
if ((getValue == null) && (!isNullable))
{
}
}
類
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace testApp.Data
{
using System;
using System.Collections.Generic;
public partial class Person
{
public int PersonId { get; set; }
public string Email { get; set; }
}
}
任何幫助,將不勝感激。
因此,您需要數據庫中可為空的屬性。 這意味着“一些魔術代碼”應該考慮到EDMX的存儲模型。 類模型不包含此信息,更不用說生成的類了。
這是如何獲取存儲模型中所有可為空的屬性的列表:
var tableName = "someTable";
var oc = ((IObjectContextAdapter)context).ObjectContext;
var items = oc.MetadataWorkspace.GetItems(DataSpace.SSpace).OfType<EntityType>();
foreach (var entityType in items.Where(e => e.Name == tableName))
{
var props = string.Join(",", entityType.Properties.Where(p => p.Nullable));
Debug.WriteLine(string.Format("{0}: {1}", entityType.Name, props));
}
您可以為此使用Nullable.GetUnderlyingType
方法
if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.