在我的 EF 4.3.1 上调用 entity.savechanges() 时出现错误。我的数据库是一个 sql ce v4 存储,我正在使用 mvvm 模式进行编码。我有一个本地版本的上下文,我将它发送到一个可观察的集合并修改等。这工作正常,当我在数据库中不存在任何行时调用 savechanges() 时,对象仍然很好。当我重新加载应用程序时,对象会按原样填充到我的列表框中,但是如果我添加另一个对象并调用 savechanges() 我会收到错误消息,指出无法将重复值插入到唯一索引中。
据我了解,这意味着上下文正在尝试将我的实体保存到数据存储中,但它似乎正在添加我未触及的原始对象以及新对象。我认为这会让他们独自一人,因为他们的状态没有改变。
private void Load()
    {
        entities.Properties.Include("Images").Load();
        PropertyList = new ObservableCollection<Property>();
        PropertyList = entities.Properties.Local;        
        //Sort the list (based on previous session stored in database)
        var sortList = PropertyList.OrderBy(x => x.Sort).ToList();
        PropertyList.Clear();
        sortList.ForEach(PropertyList.Add);
        propertyView = CollectionViewSource.GetDefaultView(PropertyList);
        if (propertyView != null) propertyView.CurrentChanged += new System.EventHandler(propertyView_CurrentChanged);     
        private void NewProperty()
    {
        try
        {
            if (PropertyList != null)
            {                                             
                Property p = new Property()
                    {
                        ID = Guid.NewGuid(),
                        AgentName = "Firstname Lastname",
                        Address = "00 Blank Street",
                        AuctioneerName = "Firstname Lastname",
                        SaleTitle = "Insert a sales title",
                        Price = 0,
                        NextBid = 0,
                        CurrentImage = null,
                        Status = "Auction Pending",
                        QuadVis = false,
                        StatVis = false, //Pause button visibility
                        Sort = PropertyList.Count + 1,                            
                    };
                PropertyList.Add(p);
                SaveProperties();
            }
        private void SaveProperties()
    {
        try
        {               
            foreach (var image in entities.Images.Local.ToList())
            {
                if (image.Property == null)
                    entities.Images.Remove(image);
            }                
        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message);
        }
        entities.SaveChanges();
    }