10

我以前从未使用过实体框架,我想尝试一些个人项目来实现它以使我的脚湿透。

我看到实体可以暴露给表示层。但我不希望暴露某些字段,例如修改日期和创建日期等字段以及各种其他数据库字段。

我如何实现业务对象并只公开我需要的属性但仍保持对象可序列化?

还有这比 LinqToSql 有什么优势?

4

4 回答 4

22

当您在 EDMX 模型中定义实体时,您可以指定每个属性的 setter 和 getter 的可见性,因此如果您不希望 ModifiedDate 在其他层中可见,您可以简单地将其指定为内部。

在此处输入图像描述

如果您的要求更复杂,例如 ModifiedDate 应该可以在实体程序集和业务逻辑程序集中访问,但不能在 UI 程序集中访问,那么您需要创建另一个对象,该对象将在业务逻辑和 UI 逻辑层之间进行交换。

于 2011-03-05T09:21:32.423 回答
3

个人在实体上使用包装类并公开或隐藏我需要的内容。

// instead of below property in your BLL:

private int m_someVariable;

public int SomeVariable
{
    get { return m_someVariable; }
    set { m_someVariable = value; }
}

// You can use the entity object:

private readonly EntityClass _entityObject = new EntityClass();

public int SomeVariable
{
    get { return _entityObject.SomeVariable; }
    set { _entityObject.SomeVariable = value; }
}

// or make it read-only at your BLL

public int SomeVariable
{
    get { return entityObject.SomeVariable; }
    // set { entityObject.SomeVariable = value; }
}
于 2011-03-05T22:43:37.497 回答
1

您只需将所需的属性绑定到表示层,这可以通过声明、业务逻辑层(具有自己的对象抽象级别)或您的 ViewModel 来完成。

于 2011-03-05T09:12:29.350 回答
1
      // this is your edmx
        Asset5Entities conx = new Asset5Entities();

// 考虑这是一个联系人的新对象列表,它是数据库中的一个表 //使用实体框架将此数据库表映射到一个对象以供您处理

            List$gt;Contact$lt; s = new List$gt;Contact$lt;();

//使用大量的 LINQ,您现在可以选择或查询您数据库中的任何表,并且您可以 // 访问该表示例(电子邮件)中的列

        var result = from q in conx.Contacts select q.Email;

// 而不是

        string sqlcommand = "select email from Contacts";
        Contact con = new Contact();
        con.Email= "xxxx@gmail.com";
        con.FirstName="nader";

        //etc etc... 



        conx.Contacts.AddObject(con);

        //rather than   " insert into Contact values ......................"

        //having your queries within ur c# code rather than strings that are not parsed //for errors but on runtime was alot helpful for me
于 2011-08-31T14:47:26.870 回答