开发者

Mapping a field name beginning with an underscore in Entity Framework 4.1 Code First

I have a class that contains a few private/protected fields and some public getters that return the value of the fields. I am attempting to map the fields to database columns using the fluent API on the DbModelBinder in OnModelCreating. I cannot use an automatic property with a protected setter so please don't offer that as a solution to my question. It would probably work I'm sure but I cannot use the automatic property as the domain class is shared code and used with other different ORMs that have different ways of mapping their fields and unfortunately one doesn't support the au

I use the following code (found on stackoverflow) to access the protected field so that I can use the expression when mapping:

public static class ObjectAccessor<T>
where T : class
{
    public static Expression<Func<T, TResult>> CreateExpression<TResult>(string propertyOrFieldName)
    {
        ParameterExpression param = Expression.Parameter(typeof(T), "propertyOrFieldContainer");
        Expression body = Expression.P开发者_运维知识库ropertyOrField(param, propertyOrFieldName);
        LambdaExpression lambda = Expression.Lambda(typeof(Func<T, TResult>), body, param);

        return (Expression<Func<T, TResult>>)lambda;
    }
}

This all works wonderfully if the field name is m_username but if I use _username I get a ModelValidationException: One or more validation errors were detected during model generation: System.Data.Edm.EdmProperty: Name: The specified name is not allowed: '_username'.

I can't use camelcase without the underscore either as the helper above can't distinguish between the public Username property and the protected username field. I'd really like to still keep using the underscore camelcase without the letter prefix.

Is it possible to configure the ModelBinder in some way so that the validation accepts the property name with a leading underscore?

Thanks in advance,

Mark


It seems that decoration of your field like this :

[Column("username")]
public string _username

maybe helpful in your case, anyway - please review similar case

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜