0

首先使用实体​​框架 6.1 代码,我尝试将导航属性与外键同步。

在 Product 上使用 foreygn 键查看我的许可证实体类:

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 不同步?怎么了?

4

1 回答 1

0

您需要在 dbset 中添加新实体

this.License = this.Entities.Licenses.Create();
this.Entities.Licenses.Add(this.License);
于 2014-05-30T08:14:24.843 回答