当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Can I assign new properties to output when selecting from a table through EF?

问题描述:

I promise all these examples will lead to some coherent point, feel free to skim, it's basic stuff until the end (and maybe even then):

public class Sample //let's say this is also a DbSet model from which EF creates a SQL tbl

{

public long Id{ get; set; }

public string Name{ get; set; }

}

I can select from that table like so:

var samples =

from sample in myDb.Samples

select new //anonymoys type

{

Id = sample.Id,

Name = sample.Name

};

or

var samples =

from sample in myDb.Samples

select new Sample //not anonymous - I don't really know what the difference is, w/e

{

Id = sample.Id,

Name = sample.Name

};

However, what if I want to select the properties of the DbSet model (/the columns in the table) AND add some custom data, for example:

var samples =

from sample in myDb.Samples

select new

{

Id = sample.Id,

Name = sample.Name

TableName = 'Samples'

};

I have tried the code above and it worked, however, I could not later edit "TableName" - was given an error stating that it's read only. I then made a new model "SampleViewModel" and gave it a TableName property, but that created the following exception:

A first chance exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Hopefully, this was clear and explains what I am asking in the title. If anyone is curious, what I am doing in practice is creating a union (.concat in EF) of 5 tables and trying to avoid putting redundant information in the tables, such as the table name. I may be missing something obvious here.

网友答案:

Anonymous classes have readonly properties. AFAIK, it's not easily possible to project into editable anonymous types with initialized properties.

You should, however, be able to project into a custom type that you've defined, but, keep in mind that doing so 'cuts you off' so to speak: after that point, you're no longer in SQL land, and it's all in memory. If you do any where conditions from there on, it will be done client-side, meaning that all candidates will be pulled to the client. That said, to do that, you'd do something like this:

var samples =
from sample in myDb.Samples
select new CustomClass
{
    Id = sample.Id,
    Name = sample.Name 
    TableName = "Samples"
};

Where CustomClass looks like this:

public class CustomClass
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string TableName { get; set; }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: