本文介绍了实体框架外键为主要关键代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有两个代码第一个模型,Foo和FooState,其中Foo有一个可选的FooState。

  public class Foo 
{
[Key]
public int FooId {get;组; }

public FooState FooState {get;组;
}

public class FooState
{
[Key]
public int FooStateId {get;组;

[必需]
public int State {get;组; }

[必需]
public Foo Foo {get;组; }
}

这样工作正常,但是当我尝试将外键添加到FooState时所以

  public class FooState 
{
[Key]
public int FooStateId {get;组;

[必需]
public int State {get;组; }

[ForeignKey(Foo)]
[必需]
public int FooId
public Foo Foo {get;组;
}

这一切都归结为因为FooStateId真的使用FooId作为主键。这从数据库的角度来看是有意义的。



然而,当保存FooState记录但仍保留必需属性时,我不需要填充Foo的实例。



这将允许我发送一个FooId和状态在一个dto,而不必从数据库中检索整个Foo对象,如果我想改变它的



我应该如何使用EF代码进行设置?

解决方案
  public class FooState 
{
[必需]
[Key]
[ForeignKey(Foo)]
public int FooStateId {get;组;

[必需]
public int State {get;组; }

public Foo Foo {get;组; }
}


I have two code first models, Foo and FooState where Foo has an optional FooState.

public class Foo
{
    [Key]
    public int FooId { get; set; }

    public FooState FooState { get; set; }
}

public class FooState
{
    [Key]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    [Required]
    public Foo Foo { get; set; }
}

This works fine however when I try to add the foreign key to FooState like so

public class FooState
{
    [Key]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    [ForeignKey("Foo")]
    [Required]
    public int FooId
    public Foo Foo { get; set; }
}

It all falls over because FooStateId is really using FooId as it's primary key. This makes sense from a database point of view.

I would however like not to have to populate an instance of Foo when saving the FooState record but still retain the required attribute.

This would allow me to send down a FooId and state in a dto and not have to retrieve the whole Foo object from the DB if I want to make a change to its state.

How should I be setting this up with EF code first?

解决方案

I thought I'd give this a shot and it worked nicely.

public class FooState
{
    [Required]
    [Key]
    [ForeignKey("Foo")]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    public Foo Foo { get; set; }
}

这篇关于实体框架外键为主要关键代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 19:34