LINQ to SQL和列别名与空格

时间:2009-05-12 14:16:43

标签: linq-to-sql

Linq还有点新鲜。这让我疯了。我想为一个列别名,别名应该有一个空格。

这很好用:

Dim q = From tmp in t.Table Select iDate = tmp.iDate

但是,我想要这个工作

Dim q = From tmp in t.Table Select "Some Alias With Space" = tmp.iDate

有什么想法吗?

7 个答案:

答案 0 :(得分:3)

首先,Alias不能有空格,就像任何变量名都不能有空格一样。我的问题是你为什么要/需要在你的名字中留一个空格?我确信有更好的方法来完成你试图实现的目标,而不是试图制定不良命名约定的不良做法。

答案 1 :(得分:2)

使用方括号在 Linq To Sql 中使用别名,如

[Some Alias With Space] = tmp.iDate

如果这不起作用,则删除空格并使用[]

答案 2 :(得分:2)

在列之前使用简单别名:

var x = from data in mdc.Accounts
select new
{
    data.AccountName,
    Total = data.CashAndEquivalent + data.MarginBalance
};

//Total is the alias

答案 3 :(得分:1)

使用数据表

DataTable dt = (from x in obj.GetAllReqVSTFs()
                select new
                    {
                        VSTF_id = x.VSTF_id,
                        x.Description,
                        x.PM1,
                        x.PM2,
                        x.Analyst_Status,
                        x.Overall_Status,
                        x.Planed_Analyst_End_Date
                    }).Take(5).ToList().ToDataTable();
foreach (DataColumn c in dt.Columns)
{
    c.ColumnName = c.ColumnName.Replace("_", " ");
}

gvBurntHours.DataSource = dt;
gvBurntHours.DataBind();

答案 4 :(得分:0)

据我所知,你不能这样做,因为列别名必须是有效的C#标识符,并且它们不允许空格。

答案 5 :(得分:0)

如果您需要将数据绑定到 gridview this 示例可以工作:

    protected void Page_Load(object sender, EventArgs e)
    {
        using (var db = new MyDataContextDataContext())
        {
            var bl2 = (from b in db.Table1 
                          select new{b.AttendanceDate, Course = b.CourseCode + " - " + b.CourseSection, b.CourseName, TeacherName = b.StaffLastName + ", " + b.StaffFirstName}
                          );

            grd.DataSource = bl2;
            grd.DataBind();  
        }
    }

    
        protected void grd_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header){
                e.Row.Cells[0].Text = "Attendance Date";
                e.Row.Cells[1].Text = "Course Code and Section";
                e.Row.Cells[2].Text = "Course Name";
                e.Row.Cells[3].Text = "Teacher Name";
    
            }
        }
    
        <asp:GridView ID="grd" class="table table-striped" runat="server" OnRowCreated="grd_RowCreated">
            <EmptyDataTemplate>
                None
            </EmptyDataTemplate>
        </asp:GridView>

答案 6 :(得分:-1)

你不能,抱歉。地狱,如果你带一个名字空间的桌子到Linq,它会自动用下划线替换空间。

除了不可能之外,这是一个非常糟糕的主意。编写Access的人应该被拍摄,因为。