Home » Microsoft Technologies

CRM 4 Custom Entities delete not removing link but deleting the associated entity

I am using MS CRM 4 and have created two custom entities (supplier and Items) each supplier can have many items assigned to it. I have further created a 1:n relationship to facilitate this.

The problem is when a user mistakenly assignes a wrong item(s) to a supplier and then decides to delete it/them he ends up deleting the item(s) in a cascade manner. Hence rather than a link between supplier and item(s) being removed the item itself is deleted form the Items list along with all other suppliers item is associated with,

I have set the relationship behaviour of 1:n to Referential where delete is set to 'remove link' but this does not work as expected.

Can you please advise how I can set-up the entities to remove the link rather then delete the item.


3 Answers Found


Answer 1

I think you got it setup the right way between Supplier and items  as a 1:N referential.  When you remove  the Supplie the items are not removed  "cacade delete" as a parential relationship.  Have you tried to republish the change and then test it again?

Answer 2

Hi Frank,

Thanks for your response. I did publish (and republish) all my changes but to no effect. Its correct, when I delete  supplier then it does not delete the associated items  (but also does not remove  the link  that appears in the lookup on the item  -even through the supplier does not exist anymore)!?! -I am unsure if this is expected  behaviour.

Any other recommendations would be greatly appreciated.




Answer 3

It sounds like your users are deleting  the Item record itself.  As you noted, The 1:n Referential relationship  has to do with how the system reacts when a Supplier is deleted, not the Item record.

To remove  the link  between a particular Item and its Supplier, your users should clear the lookup field on the Item record.  This will leave the Item in the database and remove the relationship to the Supplier.





I tried to delete a custom attribute from a custom entity and received the error below. I've confirmed twice and found no references of the attribute in any of its own views. No relationships are found (1-M, M-1 or M-M) against this column. I tried exporting customization and found that in the xml, there is a reference of that attribute in a SavedQuery used for lookup (See attribute name highlighted in XML below).

Isn't there a straight forward way to cleanup the filter hopefully leading to successful deletion of attribute.

The attribute cannot be deleted because it is referenced by the following objects. Remove all references before you delete the attribute. Note that if a deleted attribute is used in a custom report, you must manually remove it from that report.
Name: ActivityStatistic Lookup View, ParentEntity : Microsoft.Crm.Metadata.LabelCollection, Attribute Use : Filter Condition

<iscustomizable name="No">0</iscustomizable>
<isquickfindquery name="No">0</isquickfindquery>
<isuserdefined name="Yes">1</isuserdefined>
<isdefault name="Yes">1</isdefault>
<returnedtypecode formattedvalue="10,001">10001</returnedtypecode>
  <grid name="new_activitystatistics" object="10001" jump="new_uniqueidentifier" select="1" icon="1" preview="0">
    <row name="new_activitystatistic" id="new_activitystatisticid">
      <cell name="new_uniqueidentifier" width="300" />
      <cell name="new_associatedleadid" width="100" />
<customizationlevel formattedvalue="1">1</customizationlevel>
<querytype formattedvalue="64">64</querytype>
  <fetch version="1.0" mapping="logical">
    <entity name="new_activitystatistic">
      <attribute name="new_activitystatisticid" />
      <attribute name="new_uniqueidentifier" />
      <filter type="or" isquickfindfields="1">
        <condition attribute="new_crmleadid" operator="like" value="{0}" />
      <order attribute="new_uniqueidentifier" descending="false" />
      <attribute name="new_associatedleadid" />
  <LocalizedName description="ActivityStatistic Lookup View" languagecode="1033" />


I am using MS CRM 4 and have created two custom entities (supplier and Items) each supplier can have many items assigned to it. I have further created a 1:n relationship to facilitate this.

The problem is when a user mistakenly assignes a wrong item(s) to a supplier and then decides to delete it/them he ends up deleting the item(s) in a cascade manner. Hence rather than a link between supplier and item(s) being removed the item itself is deleted form the Items list along with all other suppliers item is associated with,

I have set the relationship behaviour of 1:n to Referential where delete is set to 'remove link' but this does not work as expected.

Can you please advise how I can set-up the entities to remove the link rather then delete the item.


Hello All,

I can not delete a custom entity after it was imported :(

I can not even remove the relationships existent



I have an object graph sent to a winclient via WCF. The graph looks something like this:

- Adresses (=TrackableCollection of Adres objects)

This is a many to many relation (also in the database) because we need the adress table also for adresses for other entites besides persons.

Now, on the client side I Mark a particular adress as Deleted and sent the complete object graph back to the serverside of the application.

using (Entities context = new Entities()) 
In the ApplyChanges method the folowwing code is executed and raises an exception:
// Change all the remaining relationships to the appropriate stateforeach (var relationship in allRelationships)
The error message is: "Cannot change relationship's state to the state other than deleted or detached if the source or target entity is in the deleted state."

I think this has something to do with the fact that the person entity was detached from the context (sending it out through WCF) and brought in to a new context when persisting it. But the relationship between the person and adress gets confused.

Do I have the wrong approach? Should I do some more work hand coded (other that the generated extensions on the context for Self Tracking Entities) to bring in my detached object graph ionto a newly created context? Any demystifying would be appreciated.



I the following code to associate two entities:


_dataContext.AddLink(CurrentVolunteer, "Groups", value);


This creates the link and also updates the entities in the context and is working as expected.

If I try and do the reverse and remove the association I end up with a request to delete the entity all together!


_dataContext.DeleteLink(CurrentVolunteer, "Groups", group);

Results in:

DELETE http://localhost.:51750/DataService.svc/Volunteers(5)/$links/Groups(4) HTTP/1.1

DELETE http://localhost.:51750/DataService.svc/Groups(4) HTTP/1.1

Is this a bug or am I going about it the wrong way??




I am using EF 4.0 and am generating my Entity Data Model (.edmx) file from my database. I have several foreign key constraints for Cascade OnDelete, however, these are not getting set on my associations in my entity data model. I click on the association and it shows End1 OnDelete: None.

When I check the Delete rules in my SQL Server 2008 database on my foreign key constraint, it says 'Cascade'.

Is there something I am missing to get the Cascade OnDelete flag to set for my entities in my entity data model? I am hoping I don't have to continue manually setting it everytime I load/update from my database.



Any pointers here would be much appreciated.  I have a fairly simple SL4/RIA Services application and I'm having an odd effect in the database when I delete an entity.  Instead of removing the corresponding row in the database table, it performs an update and orphans the row (clears it's foreign key value).

The code is pretty vanilla.  In my ViewModel:

        /// <summary>
        /// Wire up commands
        /// </summary>
        private void InitialiseCommands()
            DeleteCommand = new RelayCommand<PPAPDocument>(
                document => DeleteDocument(document)

        /// <summary>
        /// Removes the deleted PPAPDocument from the collection and submits changes back to the server.
        /// </summary>
        /// <param name="documentToDelete">The PPAPDocument to delete.</param>
        private void DeleteDocument(PPAPDocument documentToDelete)
            foreach (PPAPRequiredDocumentType docType in _context.PPAPRequiredDocumentTypes)
                foreach (PPAPDocument document in docType.PPAPDocuments)
                    if (document.Id == documentToDelete.Id)

        /// <summary>
        /// Submit all pending changes to the DomainService.
        /// </summary>
        public void SubmitChanges()

            // Inform listeners that data may have changed.
            Messenger.Default.Send(new NotificationMessage("ChangesSubmitted")); 


and in my DomainService:

        public void DeletePPAPDocument(PPAPDocument pPAPDocument)
            if ((pPAPDocument.EntityState == EntityState.Detached))

 Just wondering why the row is not actually deleted.  Any ideas?  Thanks!



Hi friends,

I am having a major problem. I am using Microsoft CRM 4.0 and when the user deletes an entity using the red crossed icon in the view the entity entirely gets deleted from our records. But when we use an n-n relationship the entity is NOT deleted only the relationship is deleted. Is there some way to solve this problem. I have thought of removing the button but I don't think this is nice because the users won't be satisfied with that!

Thanking you in advance,


I have an account that points to a bunch of rows in a different entity 'abc'. I need to delete those rows in entity 'abc' then insert new ones. Can anyone provide a sample code of how to delete all rows for a particular accountid (which is also a column in the 'abc' entity). Thanks so much.


Our client has a custom entity called purchase order and a child called purchase order product (not linked to the standard product entity in Dynamics). I have written a few easy quote templates in my time, but i am slightly stuck writing a custom report template (apologies in advance if this is something simple i have missed..).

I have created 2 rdl files, one called 'order', one called 'sub'.

On the 'Sub' report i have done the following:

1. created a dataset called sub with the following query

SELECT        dhc_purchaseorderid, dhc_total1, dhc_quantity1, dhc_unitcost1, dhc_name
FROM            FilteredDhc_purchaseorderproduct
WHERE        (dhc_purchaseorderid = @dhc_purchaseorderid)

2. Created a parameter called 'dhc_purchaseorderid', with a prompt called 'report_parameter_0' and a datatype of Text. Allow blank values and remain hidden.

On the 'order' report i have done the following:

1. Created a dataset called CRM with the following query

select dhc_purchaseorderid from filtereddhc_purchaseorder 

2. Added the 'sub' report to the order report and called it details, and chose my sub report. Then added a parameter



When i try running or displaying the report i get the following error:

------ Build started: Project: Report Project5, Configuration: Debug ------

[rsCompilerErrorInCode] There is an error on line 0 of custom code: [BC30037] Character is not valid.

Build complete -- 1 errors, 0 warnings

========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

I am fairly new to SSRS - so i am likely to be missing something obvious...

Any help appreciated.



Hi all

I have created some custom entities, but forgot to remove Notes and Activities relationship while creation. Now I cannot remove/delete these relationship.

Only way in the system is apparently to delete and recreate the entities. Is there anyway I can remove/hide these relationship, without having to recreate the relationships.

Thanks in advance.

Hello all,

I have a few custom entities that I cannot delete. I just get the standard "An error has occured" window which provides no help. No errors come up in the Application Error Log, either. The diagnostic tool isn't really any help, as I can't interpret anything in the massive amounts of text. I've applied the Rollup 3, and there is no change.

I have been able to delete several other custom entities, but these three won't go away for some reason. I deleted every field I could from the forms, and I deleted the relationships to everything except the Notes and Activities entities. No other customizations have been made to these entities that I can remember. Each of these entities has relationships between each other, as well, and I cannot delete those relationships. I get the same standard error when I try.

Does anyone have any suggestions on how to get around this?

Thank you.

I have created two new entities named "Client" and "Prospect" in addition to the existing default CRM entity "Account".

Each Client may have many Prospects (each Prospect can only have one Client), and each of these Prospects is linked to one Account.

i.e. Client (One to Many) ---> Prospect (One to One) ---> Account

I create activities (phone calls mostly) for each of these Prospects, and these are visible in the sidebar for the Prospect under Activity and then History once completed. I would however like these activities and history also show up in the respective Client and Account entity's Activity and History tabs to which the Prospect is linked (a single Client and a single Account).

Any suggestions as to what new database relationships need to be created?


i've created a new entity in the crm linked with contact entity, a new module, adding date and informations...

My problem is, its working fine with new contact but old one .. the date is wrong.. and I don't know how to debug this?

Thanks a lot,



 Hi Guys,

I'm a little stumped by something which should( and probably is) simple.

I'm using WCF Ria services with Silverlight 3.

Lets say I have 2 tables


ServerID - primary key


ServerID - foreign key   

(both ServerID and Hostname make up the primary key for the server table)

Now I load my a Servergroup from the database ( see the load statement in my code below)  and get it to return the related "Server" tables as well(using "Include").

That works fine.

But when I try to remove all of the Server Entities(rows) and submit the changes I get the following error.

"The value of key member 'ServerID' on an instance of an entity of type 'Server' has changed. Entity key members cannot be changed."

Am I removing the values incorrectly? Anyone know why?

My code is below. If somebody could show me what I'm doing wrong that would be great.


//Domain Service
public IQueryable<ServerGroup> GetServerGroupbyID(Guid CustomerID)
return this.ObjectContext.ServerGroup.Include("Server").Where(c => c.CustomerID.Equals(CustomerID));

//Client Code
context.Load(context.GetServerGroupbyIDQuery(WebContext.Current.User.UserID), lopServerGroupbyID_Completed, null);

void lopServerGroupbyID_Completed(LoadOperation<itc_Cloud> lo)
if (lo.HasError)

loadedGroup = lo.Entities.FirstOrDefault();

// Trying to Remove All of the Servers - Throws Error when I call submitchanges.
foreach (var item in loadedGroup.Server.ToArray())

context.SubmitChanges(); //ERROR THROWN HERE

I submitted this as a bug to MS Connect (Bug ID : 523251) but thought I'd share it with the Forum as well.

When I add a Requirements-Based Test Suite the first time it seems to work fine and pulled in the child Test Cases;  however, after deleting and re-adding the same User Story to my Test Plan, the Test records no longer come over.

I discovered that what is occurring here is that the Delete action with the Testing Center Test plan under a Requirements-Based Test Suite is actually removing the Requirement-->Test Case parent-child link.   So when I try to re-add this requirement the Test Cases no longer come over.

Steps to Reproduce
1. Defined a Parent Child Relationship between a Requirement and a set of Test Cases
2. Open MTLM and create a Test Suite using the Add Requirement to pull in the the Test Cases
3. Delete the Test Cases within MTLM
4. Repeat step 2 above

Actual Results
No Test Cases added due to the parent-child link being deleted

Expected Results
Parent-child link should not be altered from within MTLM, at least not via this action which is not expected.


Hi, Friends,

                     I want to map the attributes of CRM and GP entities..I want to find the entities in GP corresponds to Account, Order and Product..Pls help me to do that



                   I had created a dynamic entity and properties to it by using



na = newDynamicEntity();

na.Name =



StringProperty MyAccountName = newStringProperty();

MyAccountName.Name =


MyAccountName.Value =



newProperty[] { MyAccountName};


StringProperty MyAccountNo = newStringProperty();

MyAccountNo.Name =


MyAccountNo.Value =


na.Properties= newProperty[] { MyAccountNo};

                      when doing like this, only the last added propety is created in CRM( here, only accountnumber is saved in CRM)..I want to create an account  with the name 'Greg' and account number '1234596'...I can use

na.Properties= newProperty[] { MyAccountName,MyAccountNo};

But ,is there is any other alternative to do this?


Hi Friends,

                  I want to retreive and update dynamic entity in crm..For retrieving, I tried the following code

         // Create the retrieve target.
            TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

            // Set the properties of the target.
            targetRetrieve.EntityName = EntityName.contact.ToString();
            targetRetrieve.EntityId = created.id;

            // Create the request object.
            RetrieveRequest retrieve = new RetrieveRequest();

            // Set the properties of the request object.
            retrieve.Target = targetRetrieve;
            // Be aware that using AllColumns may adversely affect
            // performance and cause unwanted cascading in subsequent
            // updates. A best practice is to retrieve the least amount of
            // data required.
            retrieve.ColumnSet = new AllColumns();

            // Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
            retrieve.ReturnDynamicEntities = true;

            // Execute the request.
            RetrieveResponse retrieved = (RetrieveResponse) service.Execute(retrieve);

            // Extract the DynamicEntity from the request.
            DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;

                          But there is an error in the following line

  targetRetrieve.EntityId = created.id;

                                "the name 'created' does not exist in the current context"...Why this happen? I am using crm web services(not sdk)..How can I specify the entity id?..ppls help me to do this


I have an event form. The event has existing   3 to 4 trips.

When ever I click on new event tab, the existing Trips  should be populated in a datagrid.

I have an event entity and Trip Entity

How to do this using crm grid?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure