如何同步导航属性和外键?

时间:2014-05-27 07:33:11

标签: c# entity-framework-6.1

首先使用enttity framework 6.1代码,我尝试将导航属性与外键同步。

在Product:

上查看带有foreygn密钥的License实体的课程
public partial class License
{
    [Key]
    public int Id { get; set; }
    [Required]
    public System.Guid Guid { get; set; }
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public System.DateTime CreationDate { get; set; }
    [Required]
    public int ProductId { get; set; }
    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
}

在winform代码中,我创建了一个许可证实体,并在组合框的选定值更改事件中设置了产品导航属性:

public partial class NewLicenseForm : Form
{
    public NewLicenseForm()
    {
        InitializeComponent();
        this.Entities = ServicesProvider.GetService<Entities>();
        this.License = this.Entities.Licenses.Create();
    }

    public Entities Entities
    {
        get;
        private set;
    }

    public License License
    {
        get;
        private set;
    }

    private void productsComboBox_SelectedValueChanged(object sender, EventArgs e)
    {
        ComboBox productsComboBox = sender as ComboBox;
        if(productsComboBox == null)
            return;

        if(productsComboBox.SelectedValue != null)
        {
            this.License.Product = this.Entities.GetProductById((int)productsComboBox.SelectedValue);
        }
    }
}

为什么在设置导航属性时不会同步this.License.ProductId?怎么了?

1 个答案:

答案 0 :(得分:0)

您需要在dbset中添加新实体

this.License = this.Entities.Licenses.Create();
this.Entities.Licenses.Add(this.License);