实体框架和一对多关系代码优先

时间:2014-05-14 23:11:41

标签: entity-framework ef-code-first

我一直无法理解我认为的简单关系模型。我有一个CloudFile对象代表CDN上的文件。我还有另外两个与Creative相关的对象MerchantCloudFile

我的CloudFile类

public class CloudFile
{
    [Key]
    public int CloudFileId { get; set; }

    [StringLength(50)]
    public string OriginalFileName { get; set; }

    [StringLength(100)]
    public string Name { get; set; }

    [StringLength(5)]
    public string FileExt { get; set; }

    public int Height { get; set; }
    public int Width { get; set; }
    public long SizeInBytes { get; set; }
    public DateTime DateCreated { get; set; }

    public CloudFile()
    {
        this.DateCreated = DateTime.Now;
    }
}

我的广告素材类

public class Creative
{
    [Key]
    public int CreativeId { get; set; }

    [Required]
    public int OfferId { get; set; }
    public virtual Offer Offer { get; set; }

    public virtual CloudFile CloudFile { get; set; }

    [StringLength(100)]
    public string Alt { get; set; }

    public DateTime DateCreated { get; set; }

    public Creative()
    {
        this.DateCreated = DateTime.Now;
        this.CloudFile = new CloudFile();
    }
}

我的商家类

public class Merchant
{
    #region Keys
    [Key]
    [Display(Name = "Merchant ID")]
    public int MerchantId { get; set; }
    #endregion

    [Required]
    [Display(Name = "Merchant Name")]
    [StringLength(256)]
    public string Name { get; set; }

    public virtual CloudFile CloudFile { get; set; }

    public ICollection<Offer> Offers { get; set; }
    public ICollection<MerchantLocation> Locations { get; set; }

    public Merchant()
    {
        this.Offers = new List<Offer>();
        this.Locations = new List<MerchantLocation>();
    }

我不确定如何在数据库中正确关联和保存这些对象。我尝试将新的CloudFile对象添加到Merchant.CloudFile,然后运行以下命令:

    ......
    merchant.CloudFile = new CloudFile() {...set properties here...};
    MerchantDB.Modify(merchant);
    ......

    public static bool Modify(Merchant merchant)
    {
        using (AppDbContext db = new AppDbContext())
        {
            db.Entry(merchant).State = EntityState.Modified;

            //Return true if only 1 record was modified.  If not, return false.
            return (db.SaveChanges() == 1);
        }
    }

但它不会保存CloudFile并将其与Merchant关联。我可以直接将CloudFile保存到CloudFile表,但仍然没有关联。

感谢您提前协助!

1 个答案:

答案 0 :(得分:0)

那是因为你没有提到双向关系,即没有从你的cloudtfile到广告素材和商家类的导航属性,请尝试将以下行添加到你的cloudfile模型中

public Creative creativeObj { get; set; }
public Merchant merchantObj { get; set; }

也改变了

db.Entry(merchant).State = EntityState.Modified; 

db.Entry(cloudfile).State = EntityState.Modified;