如何检查属性类型是ef 6中的字符串?

时间:2018-01-26 07:52:53

标签: c# entity-framework

您好我正在尝试在已更改的实体中设置用户ID列,如果实体具有“UserID”列且列类型为String。我能够使用以下代码检查'UserID'存在但不知道如何确认其类型是String。你能帮忙吗?

List<DbEntityEntry> modifiedChanges = ChangeTracker.Entries().Where(x =>
                    x.State == EntityState.Added || x.State == EntityState.Modified)
                    .ToList();

foreach (var change in modifiedChanges)
{
    if (change.CurrentValues.PropertyNames.Contains("UserID"))
    {
        /* TODO: How to check property type is string? */
        change.Property("UserID").CurrentValue = userID;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

List<DbEntityEntry> modifiedChanges = ChangeTracker.Entries().Where(x =>
                    x.State == EntityState.Added || x.State == EntityState.Modified)
                    .ToList();

foreach (var change in modifiedChanges)
{
    if (change.CurrentValues.PropertyNames.Contains("UserID"))
    {
        if (change.Entity.GetType().GetProperty("UserID").PropertyType == typeof(string))
        {
           change.Property("UserID").CurrentValue = userID;
        }
    }
}