gpt4 book ai didi

c# - 在 Entity Framework Code First 中映射列

转载 作者:IT王子 更新时间:2023-10-29 04:01:49 26 4
gpt4 key购买 nike

我在尝试将我的 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");
}
);
}
}

我希望我的 table 是:

tblDinners  
colID
colHost
colDate
colTitle
colAddress

我收到这个错误:

The properties expression 'c => new <>f__AnonymousType0`5(colID = c.DinnerID, colTitle = c.Title, colHost = c.HostedBy, colDate = c.EventDate, colAddress = c.Address)' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'.

映射列的正确语法是什么?

如果你让我知道如何将 Address 属性映射到一个名为 Address 的子类中,可加分:

public class Address
{
City
State
Zip, etc
}

最佳答案

我相信你只需要做

modelBuilder.Entity<Dinner>().Property(x => x.HostedBy).HasColumnName("colHost");

对于您希望数据库列名称的命名方式与其属性名称不同的所有列。


编辑: 经过更多搜索,我发现了 this question .从那个和你发布的错误来看,似乎 mc.Properties() 更适合将值拆分到不同的表中,而不是实际重命名这些表名。我认为重命名仍然需要手动完成。

这又是来自谷歌搜索的信息,我不知道我是否只是错过了一 block 来做你想做的事:)。

关于c# - 在 Entity Framework Code First 中映射列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6061994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com