我在尝试将我的EF 4.1 Code First模型映射到数据库时遇到了问题。当数据库与代码完全匹配时,一切都正常,但是当我尝试映射名称不同的列时,就会遇到问题。
我按照教程进行操作,该教程可能是使用CTP版本构建的,因为一些方法已经丢失/不同。
我的模型如下:
public class Dinner
{
public int DinnerID { get; set; }
public string HostedBy { get; set; }
public DateTime EventDate { get; set; }
public string Title { get; set; }
public string Address { get; set; }
}
public class NerdDinners : DbContext
{
public DbSet<Dinner> Dinners { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// THIS IS WHAT I TRIED BUT IT IS FAILING
modelBuilder.Entity<Dinner>().Map(mc =>
{
mc.Properties(c => new {
colID = c.DinnerID,
colTitle = c.Title,
colHost = c.HostedBy,
colDate = c.EventDate,
colAddress = c.Address
});
mc.ToTable("tblDinner");
}
);
}
}
我希望我的表格是:
tblDinners
colID
colHost
colDate
colTitle
colAddress
我遇到了这个错误:
在属性表达式中, 'c => new <>f__AnonymousType0`5(colID = c.DinnerID, colTitle = c.Title, colHost = c.HostedBy, colDate = c.EventDate, colAddress = c.Address)' 是无效的。该表达式应该表示一个属性: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'。当指定多个属性时,请使用匿名类型: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'。
如何正确映射列?
如果您想将 Address 属性映射到名为 Address 的子类中,则可以使用以下代码:
```csharp public class Dinner { // other properties public Address Address { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } } ```
public class Address
{
City
State
Zip, etc
}