我以前从未使用过实体框架,我想尝试一些个人项目来实现它,以便入门。
我发现实体可以暴露给表示层。但是我不希望某些字段暴露出来,例如修改日期和创建日期以及其他各种数据库字段。
我应该如何实现业务对象并仅公开所需的属性,但仍使对象可序列化?
此外,这与LinqToSql相比有哪些优势?
我发现实体可以暴露给表示层。但是我不希望某些字段暴露出来,例如修改日期和创建日期以及其他各种数据库字段。
我应该如何实现业务对象并仅公开所需的属性,但仍使对象可序列化?
此外,这与LinqToSql相比有哪些优势?
在EDMX模型中定义实体时,您可以指定每个属性的setter和getter的可见性,因此如果您不希望ModifiedDate在其他层中可见,只需将其指定为internal。
如果您的要求更加复杂,例如ModifiedDate应该在实体程序集和业务逻辑程序集中可访问,但不能在UI程序集中访问,则需要创建另一个对象,在业务逻辑和UI逻辑层之间进行交换。
个人建议在实体类上使用包装类,并公开或隐藏需要的内容。
// 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; }
}
BLL
类标记为 serializable
并遵循规则即可。我思考了一段时间这个解决方案,它对我很有效。我更喜欢这种方法,因为您可以在独立项目中声明它,而不需要向实体项目添加任何 partial class
(在我的情况下,两个不同的团队正在每个项目上工作)。这种解决方案有一些技巧,例如创建两个构造函数,一个是无参数的,另一个接受一个实体对象... - Xaqron // 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
只需将所需属性绑定到表示层,这可以通过声明、业务逻辑层(具有自身的对象抽象级别)或 ViewModel 完成。