Я просмотрел довольно много потоков о посеве отношений один к многим с EF, но не может найти ответа на то, что кажется простым вопросом. Как это сделать? У меня есть следующий код, где я пытаюсь создать объект AuctionItem, а затем добавлять к нему объекты AuctionImage. Но я получаю исключение null для аукционаOne.AuctionImages на аукционе lineOne.AuctionImages.Add() ... Может ли кто-нибудь сказать мне, что я делаю неправильно? Благодаря!Поселение от одного до многих отношений с каркасом сущности
protected override void Seed(AuctionDbContext db)
{
var auctionOne = new AuctionItem()
{
AuctionComplete = string.Empty,
AuctionDate = DateTime.Now.AddDays(-1),
CurrentPrice = 2,
EndPrice = 5,
InitialPrice = 1,
InitialQuantity = 1,
LongDescription = "Long description",
PriceDrops = 2,
QuantityRemaining = 2,
ReserveQuantity = 1,
RetailPrice = 4,
ShortDescription = "Short description",
Title = "Auction one"
};
auctionOne.AuctionImages.Add(new AuctionImage
{
Description = "Beautiful picture",
Filename = "picture.jpg"
});
db.AuctionItems.Add(auctionOne);
base.Seed(db);
}
И вот мои занятия.
public class AuctionItem
{
[Key]
public int AuctionItemID { get; set; }
[Column(TypeName = "varchar"), MaxLength(256)]
public string Title { get; set; }
public decimal InitialPrice { get; set; }
public int InitialQuantity { get; set; }
public DateTime? AuctionDate { get; set; }
[Column(TypeName = "varchar(max)")]
public string ShortDescription { get; set; }
[Column(TypeName = "varchar(max)")]
public string LongDescription { get; set; }
public decimal RetailPrice { get; set; }
public decimal? EndPrice { get; set; }
public decimal CurrentPrice { get; set; }
public int PriceDrops { get; set; }
public int QuantityRemaining { get; set; }
public int ReserveQuantity { get; set; }
[Column(TypeName = "char"), MaxLength(10)]
public string AuctionComplete { get; set; }
[Column(TypeName = "xml")]
public string Metadata { get; set; }
public virtual ICollection<AuctionImage> AuctionImages { get; set; }
}
public class AuctionImage
{
[Key]
public int AuctionImageID { get; set; }
[ForeignKey("AuctionItem")]
public int AuctionItemID { get; set; }
public virtual AuctionItem AuctionItem { get; set; }
[Column(TypeName = "varchar"), MaxLength(256)]
public string Description { get; set; }
[Column(TypeName = "varchar(max)")]
public string Filename { get; set; }
[Column(TypeName = "xml")]
public string MetaData { get; set; }
}
Хорошо, спасибо. Это на самом деле то, что я изначально считал, но полагал, что EF автоматически создаст коллекцию для меня, чтобы добавлять к ней элементы. Думаю нет. Благодаря! –