T>使用DataContext.ExecuteQuery&LT时忽略只读类属性;类属、DataContext、gt、LT

2023-09-03 12:32:50 作者:4.挽弦暮笙

我如何告诉LINQ数据上下文忽略任何特定的属性,或者所有的只读属性,绑定一个结果集对象时?

我正在与一些T-SQL语句,很难使用LINQ EX preSS,所以我使用的数据上下文的executeQuery方法通过直T-SQL数据库。

如果我的类T有任何只读属性,我得到的运行时异常时的数据上下文试图设置其属性和失败,因为没有setter属性。我如何告诉上下文忽略这些属性?

这是我在做什么了。它的工作原理,但它吮吸:

 公共BOOL IsPaidInFull {
    {返回NetTotal< =0米; }
    集合{/ *必要的,这样的LINQ不会呛。千万不要用手*设置/}
}
 
解决java,sql.SQLException Can not issue data manipulation statements with executeQuery

解决方案

你有没有考虑LINQ到实体?它可能不值得麻烦您的项目进行转换,这取决于你的ORM走多远你是,或有多少开销是舒服。然而,这个确切的情况将不会是一个问题在LINQ to实体。它不会尝试更新的对象加载它时只读属性,因为他们没有被明确映射,它们仅仅是扩展属性。

此外,您还可以通过使用替代属性的getter函数去老派/ java的路径。公共BOOL getIsPaidInFull(){返回NetTotal< =0米;}。

或者你可以在继承的子类实现只读属性玩耍,但可能会引入各种各样的类型的问题。

How do I tell a LINQ data context to ignore either specific properties, or all readonly properties, when binding a result set to an object?

I am working with some T-SQL statements that are difficult to express using LINQ, so I'm using the ExecuteQuery method of the data context to pass the straight T-SQL to the database.

If my class T has any readonly properties, I get exceptions at runtime when the data context tries to set those properties and fails because there's no setter property. How do I tell the context to ignore those properties?

This is what I'm doing now. It works, but it sucks:

public bool IsPaidInFull {
    get { return NetTotal <= 0m; }
    set { /* needed so linq doesn't choke. Should never be set by hand */ }
}

解决方案

Have you considered Linq to Entities? It may not be worth the trouble to convert your project, depending on how far along you are, or how much orm overhead you are comfortable with. However, this exact scenario would not be a problem in Linq to Entities. It does not try to update read only properties in the object when loading it, because they are not explicitly mapped, they are simply extension properties.

Also, you could go the old-school/java route by using getter functions instead of properties. public bool getIsPaidInFull(){return NetTotal <= 0m;}.

Or you could play around with implementing the read only properties in an inherited child class, but that may introduce all sorts of type issues.