自從我上次使用EF以來已經有相當長的一段時間了。我以前從未遇到任何問題。現在我試圖插入一個與另一個對象有一對多關係的對象。但在API調用中,子對象的集合數組顯示爲空,但可以在子對象的api調用中看到父對象。對象不添加兒童 - EF代碼優先
我有我的模型如下:
會話表
public class Conversation
{
public Conversation()
{
this.ChatMessages = new List<ChatMessage>();
this.DeletedConversations = new List<ConversationDeleted>();
}
public int ConversationID { get; set; }
public string toUser { get; set; }
public string FromUser { get; set; }
[InverseProperty("Conversation")]
public ICollection<ChatMessage> ChatMessages { get; set; }
public ICollection<ConversationDeleted> DeletedConversations { get; set; }
public DateTime CreatedAt { get; set; }
public int UserID { get; set; }
}
ChatMessage表
public class ChatMessage
{
public int ChatMessageID { get; set; }
public string fromUser { get; set; }
public string toUser { get; set; }
public string Message { get; set; }
public bool DeliveryStatus { get; set; }
public DateTime CreatedAt { get; set; }
public Guid UniqueID { get; set; }
public int ConversationID { get; set; }
[ForeignKey("ConversationID")]
public virtual Conversation Conversation { get; set; }
public ICollection<MessageDeleted> MessagesDeleted { get; set; }
public int UserId { get; set; }
}
我流利的API看起來是這樣的:
modelBuilder.Entity<ChatMessage>()
.HasRequired(x => x.Conversation)
.WithMany(x => x.ChatMessages)
.HasForeignKey(x => x.ConversationID);
我正在嘗試創建一個對話實體並向它的集合中添加一個聊天對象。我這樣做,像這樣:
public IHttpActionResult CreateConversation()
{
ChatMessage msg = new ChatMessage { CreatedAt = DateTime.UtcNow, DeliveryStatus = true, fromUser = "annettehiggs", toUser = "terrydriscoll", Message = "Hum tum", UniqueID = Guid.NewGuid(), UserId = 43 };
Conversation conv = new Conversation();
conv.ChatMessages.Add(msg);
conv.CreatedAt = DateTime.UtcNow;
conv.FromUser = "annettehiggs";
conv.toUser = "terrydriscoll";
DataModel db = new DataModel();
db.Conversations.Add(conv);
db.SaveChanges();
return Ok(conv);
}
,這是我如何獲得一個談話對象:
public IQueryable<Conversation> GetConversations()
{
return db.Conversations;
}
結果,ChatMessage API調用顯示了它的相關的談話,但談話的對象不在收藏中顯示聊天。我在這裏做錯了什麼?
保存數據還是檢索問題?您分享的代碼是爲了保存。 – sachin