{"record":{"id":"7abeaf5793ba16a9","repo":"dotnet/efcore","slug":"the-view-view-cannot-be-used-for-entity-type-7abeaf","errorCode":null,"errorMessage":"The view '{view}' cannot be used for entity type '{entityType}' since it is being used for entity type '{otherEntityType}' and there is no relationship between their primary keys.","messagePattern":"The view '(.+?)' cannot be used for entity type '(.+?)' since it is being used for entity type '(.+?)' and there is no relationship between their primary keys\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs","lineNumber":1360,"sourceCode":"                if (mappedType.BaseType != null)\n                {\n                    var principalType = mappedType.FindForeignKeys(mappedType.FindPrimaryKey()!.Properties)\n                        .First(fk => fk.PrincipalKey.IsPrimaryKey()\n                            && unvalidatedTypes.Contains(fk.PrincipalEntityType))\n                        .PrincipalEntityType;\n                    throw new InvalidOperationException(\n                        RelationalStrings.IncompatibleViewDerivedRelationship(\n                            storeObject.DisplayName(),\n                            mappedType.DisplayName(),\n                            principalType.DisplayName()));\n                }\n\n                continue;\n            }\n\n            if (root != null)\n            {\n                throw new InvalidOperationException(\n                    RelationalStrings.IncompatibleViewNoRelationship(\n                        storeObject.DisplayName(),\n                        mappedType.DisplayName(),\n                        root.DisplayName()));\n            }\n\n            root = mappedType;\n        }\n\n        Check.DebugAssert(root != null);\n        unvalidatedTypes.Remove(root);\n        var typesToValidate = new Queue<IEntityType>();\n        typesToValidate.Enqueue(root);\n\n        while (typesToValidate.Count > 0)\n        {\n            var entityType = typesToValidate.Dequeue();\n            var typesToValidateLeft = typesToValidate.Count;","sourceCodeStart":1342,"sourceCodeEnd":1378,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs#L1342-L1378","documentation":"The view-sharing analog of error 430. Two or more entity types mapped to the same view must be connected by inheritance or a PK-to-PK foreign key. The validator at line 1358-1365 throws IncompatibleViewNoRelationship when it encounters a second 'root' view-mapped type with no connecting relationship to the first.","triggerScenarios":"Calling `.ToView(\"SameView\")` on two unrelated entity types without a foreign key between their primary keys. Detected during the initial root-finding loop in ValidateSharedViewCompatibility.","commonSituations":"Backing two read-only query entities by the same database view without defining the relationship; renaming views to collide; keyless entities mapped to a shared view without an ownership link.","solutions":["Define a foreign key between the primary keys of the two view-mapped entity types.","Model one entity as owned by the other (.OwnsOne) so EF creates the implicit relationship.","Map the unrelated entity to its own view or to a table."],"exampleFix":"// before\nmodelBuilder.Entity<OrderSummary>().ToView(\"v_Orders\");\nmodelBuilder.Entity<OrderStats>().ToView(\"v_Orders\"); // no FK\n\n// after\nmodelBuilder.Entity<OrderStats>()\n    .HasOne<OrderSummary>()\n    .WithOne()\n    .HasForeignKey<OrderStats>(s => s.Id);\nmodelBuilder.Entity<OrderSummary>().ToView(\"v_Orders\");\nmodelBuilder.Entity<OrderStats>().ToView(\"v_Orders\");","handlingStrategy":"validation","validationCode":"var byView = modelBuilder.Model.GetEntityTypes()\n    .Where(e => !e.IsMappedToJson() && e.GetViewName() is not null)\n    .GroupBy(e => (e.GetViewName(), e.GetViewSchema()))\n    .Where(g => g.Count() > 1);\nforeach (var grp in byView)\n{\n    var types = grp.ToList();\n    for (int i = 1; i < types.Count; i++)\n    {\n        bool connected = types[i].BaseType != null && types.Contains(types[i].BaseType)\n            || HasIdentifyingFk(types[i], types[0])\n            || HasIdentifyingFk(types[0], types[i]);\n        if (!connected)\n            throw new InvalidOperationException(\n                $\"View '{grp.Key.Item1}' shared by {types[0].Name} and {types[i].Name} without a linking FK.\");\n    }\n}\nbool HasIdentifyingFk(IEntityType dep, IEntityType prin)\n    => dep.FindPrimaryKey() is { } pk\n       && dep.FindForeignKeys(pk.Properties).Any(fk =>\n            fk.PrincipalKey.IsPrimaryKey() && fk.PrincipalEntityType == prin);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["When two entity types share a view, define a FK between their primary keys or use ownership.","Treat view-backed query models like tables for relationship requirements.","Add a CI test that every shared-view group is a single connected component."],"tags":["ef-core","views","model-validation","relationships"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}