在MVC4 EF CodeFirst中创建关系时,为什么我们需要同时包含Object和ObjectId?

Rob*_*ous 2 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

例如,在将卡片与套件相关联时,我有:

public class Card
{

    public virtual int CardId { get; set; }

    // belongs to a Set
    public virtual int SetId { get; set; }
    public virtual Set Set { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

为什么我需要Set和SetId?

amh*_*hed 5

您无需进行设置.您可以将"Set"指定为虚拟对象,以便在运行时使用navigational属性覆盖它.实体框架将自动在表上创建外键"SetId",即使您无法从对象域模型访问它.

您不需要设置它,但我个人喜欢访问我的对象上的底层外键ID,因为我可以指定与int的关系,而不必实例化相关对象.

编辑:添加示例代码

有以下课程:

public class Card
    {
        public virtual int CardId { get; set; }

        // belongs to a Set
        public virtual int SetId { get; set; }
        public virtual Set Set { get; set; }
    }

    public class Set
    {
        public int SetId { get; set; }
        public string SetName { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

    var context = new Context(); //Db Code-First Context

    var set = context.Sets.First(s => s.SetName == "Clubs"); //Get the "Clubs" set object

    //Assign the set to the card
    var newCard = new Card();
    newCard.Set = set; 

    //Save the object to the databae
    context.Cards.Add(newCard);
    context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

或者做这样的事情:

//Assign the set ID to the card
var newCard = new Card();
newCard.SetId = 4; 

//Save the object to the databae
context.Cards.Add(newCard);
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

并且对象将以相同的方式存储.

想象一下,您正在将ViewModel发布到控制器.从视图而不是整个对象的下拉列表中传递选定的Id更容易.