【问题标题】:How to synchronize navigation property and foreign key?如何同步导航属性和外键?
【发布时间】:2014-05-27 07:33:10
【问题描述】:

首先使用实体​​框架 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 不同步?怎么了?

【问题讨论】:

  • 你的 DBContext 在哪里?您何时保存实体?您是否启用了更改跟踪代理?
  • 我的 DBContext 是 this.Entities,我不想保存实体,我启用了更改跟踪代理

标签: c# entity-framework-6.1


【解决方案1】:

您需要在 dbset 中添加新实体

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2011-08-09
    相关资源
    最近更新 更多