我在这里搜索了很多问题,听起来和我的很相似,但没有一个符合我的问题,所以我希望在这张票中得到一些帮助..
我使用 EF Code First 并尝试将其映射到现有(遗留)MySQL 数据库。在我的属性上工作正常,除了一个,我不明白为什么..
为空的模型:
[Table("einheitenstamm")]
public class Unit : ClassicEntity
{
[Key]
[Column("estID")]
public int Id { get; set; }
[Column("estEinheit")]
public string Name { get; set; }
}
包含对 Unit 的引用的模型:
[Table("artikeldaten_preise")]
public class ArticlePrice : ClassicEntity
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("einheit")]
[ForeignKey("Id")]
public virtual Unit Unit { get; set; } /* is always null!!!!! */
[Column("preisliste")]
[ForeignKey("Id")]
public virtual Pricelist Pricelist { get; set; } /* gets loaded without problems */
[Column("artikel")]
[ForeignKey("Id")]
public virtual Article Article { get; set; } /* gets loaded without problems */
[Column("preis")]
public double Price { get; set; }
}
创建数据库表:
CREATE TABLE `artikeldaten_preise` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`preisliste` INT(11) NOT NULL,
`artikel` VARCHAR(10) NOT NULL,
`preis` DECIMAL(10,2) NOT NULL,
`einheit` INT(11) NOT NULL,
`changed` DATETIME NULL DEFAULT NULL,
`sys_deleted` BIT(1) NOT NULL DEFAULT b'0',
`sys_changedfrom` VARCHAR(50) NULL DEFAULT NULL,
`sys_changedat` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `artikel` (`artikel`) USING BTREE,
INDEX `preisliste` (`preisliste`) USING BTREE,
INDEX `einheit` (`einheit`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2;
代码:
var units = from unit in context.Units
where unit.Id == 4
select unit;
foreach (var unit in units)
Console.WriteLine(unit.Id + ": " + unit.Name); /* works */
var prices = from price in context.ArticlePrices
select price;
foreach (var price in prices.ToList()) /* price.Unit = NULL ........... */
MessageBox.Show(price.Article.Description + " " + price.Price + "/"
+ price.Unit.Name + " in pricelist '"
+ price.Pricelist.Name + "'");
谁能告诉我我做错了什么?
最佳答案
您必须显式定义关系并为每个导航属性创建一个 xxId 属性,然后您可以使用相应的 ForeignKey 属性对其进行修饰。这里不需要“真正的”外键..
[Table("artikeldaten_preise")]
public class ArticlePrice : ClassicEntity
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("einheit")]
public int UnitId { get; set; }
[ForeignKey("UnitId")]
public virtual Unit Unit { get; set; }
[Column("preisliste")]
public int PricelistId { get; set; }
[ForeignKey("PricelistId")]
public virtual Pricelist Pricelist { get; set; }
[Column("artikel")]
public int ArticleId { get; set; }
[ForeignKey("ArticleId")]
public virtual Article Article { get; set; }
[Column("preis")]
public double Price { get; set; }
}
关于c# - Entity Framework 5.0 - 1 对 1 关系无故为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985598/