开发者

Storing a Models private property with MVC and EF4

Contrived example, but with 'code first' EF4 could I store in the database a private property.

E.g. assuming we didn't want t开发者_如何学JAVAhe caller to know the current BarCount or maximum range :-

    public class Foo
    {        
        public string FooName { get; set; }

        // How to ensure this is stored in DB?
        private int BarCount { get; set; }

        public void IncBarCount()
        {
            BarCount++;
        }

        public bool IsBarCountInRange()
        {
            return BarCount < 10;
        }
    }


If you want to hide this information from the caller, you obviously don't expect him, to modify the entity directly. You could create a base-class for Foo that contains only those properties, you want the caller to see.

public abstract class FooBase 
{
     public string FooName { get; set; }
}

public class Foo : FooBase
{
     public int BarCount { get; set; }
}

You could then return an instance of FooBase rather than Foo to the caller. BUT if the caller has a reference to your object, he could always somehow access hidden information using Reflection.

Another possible option would be do declare an Interface and have Foo implement it explicitly, although I don't know how EF-Code First would react to that. I use an approach where I create POCO classes and the mapping fragments (SSDL, CSDL and MSL files) from hand, from which I've learned, that EF can work with Types marked as internal. But I don't know whether applies to Code-First too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜