gpt4 book ai didi

entity-framework-4.1 - EF 导航属性和映射问题

转载 作者:行者123 更新时间:2023-12-02 02:17:50 24 4
gpt4 key购买 nike

一开始我想提一下,我已经为这个问题奋斗了几天,并尝试了很多或多或少与这个问题相关的答案。但是我无法解决它。

我有两个类代表数据库中的表。这些是遗留应用程序使用的现有表,我无法更改它们。

消息可以有多个消息接收者。

环境:MVC3、EF4.1

类是:

public class Message
{
[ForeignKey("MessageReciepients")]
public virtual int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }
[ForeignKey("User")]
public int AuthorUserID { get; set; }

//P\\ Navigation properties
public virtual IList<MessageRecipient> MessageReciepients { get; set; }
public virtual User User { get; set; }
}

public class MessageRecipient
{
//[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }
public int UserID { get; set; }
public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }

//P\\ Navigation Properties
public virtual User User { get; set; }
}

我的错误是:

The foreign key component 'MessageID' is not a declared property on type 'MessageRecipient'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

如何正确映射这些类、关系来加载消息的接收者?

我可以补充一点,导航属性 User 可以正确地处理消息并正确加载用户的数据。

我对 .NET 不是很熟悉,但我是边做边学的。我尝试了一些 EF API 配置来映射这些我尝试对它发誓、诅咒它,同时几乎要哭泣和祈祷。不开心!!

非常感谢您的帮助。

最佳答案

原来问题出在我需要使用的复合键上,这一切都可以通过一些属性来解决:

现在是这样的:

public class Message
{
public int MessageID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Recieved { get; set; }

[ForeignKey("User")]
public int AuthorUserID { get; set; }

//P\\ Navigation properties
public virtual ICollection<MessageRecipient> MessageRecipients { get; set; }
public virtual User User { get; set; }
}

public class MessageRecipient
{
[Key, Column(Order=0), ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserID { get; set; }

[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MessageID { get; set; }

public bool Read { get; set; }
public bool Important { get; set; }
public bool Deleted { get; set; }
public bool Destroyed { get; set; }

//P\\ Navigation Properties
public virtual User User { get; set; }
}

关于entity-framework-4.1 - EF 导航属性和映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9637492/

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