EF Core - create relationship without primary/foreign keys - c#

I'm trying to configure EF to include documents when retriving a user or product. The entity Document has a ReferenceId property which should store either UserId or ProductId. This way, when I save a document for a user or product, the UserId or ProductId is saved to Document.ReferenceId.
Entities:
public class User
{
public string Id { get; set; }
public ICollection<Document> Documents { get; set; }
}
public class Product
{
public string Id { get; set; }
public ICollection<Document> Documents { get; set; }
}
public class Document
{
public string Id { get; set; }
public string ReferenceId { get; set; }
}
Configuring:
builder.Entity<User>(e =>
{
e.HasKey(e => e.Id);
e.Property(p => p.Id).ValueGeneratedOnAdd();
e.HasMany(e => e.Documents)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<Product>(e =>
{
e.HasKey(e => e.Id);
e.Property(p => p.Id).ValueGeneratedOnAdd();
e.HasMany(e => e.Documents)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<Document>(e =>
{
e.HasKey(e => e.Id);
e.Property(p => p.Id).ValueGeneratedOnAdd();
e.ToTable("Documents");
});
Saving:
var user = new User { };
var userDocument = new Document { ReferenceId = user.Id };
var product = new Product { };
var productDocument = new Document { ReferenceId = product.Id };
_context.Users.Add(user);
_context.Products.Add(product);
_context.Add(userDocument);
_context.Add(productDocument);
_context.SaveChanges();
Migrations:
migrationBuilder.CreateTable(
name: "Documents",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ReferenceId = table.Column<string>(nullable: true),
ProductId = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Documents", x => x.Id);
table.ForeignKey(
name: "FK_Documents_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Documents_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
I don't want 2 foreign keys (ProductId and UserId) to be created on Documents table. Is there a way to make EF automatically link UserId and ProductId to ReferenceId?

The proper way to solve it would be to have User and Product inherit a base class and move the Id and Documents properties to that class.
public class BaseObject
{
public string Id { get; set; }
public ICollection<Document> Documents { get; set; }
}
public class User : BaseObject
{
}
public class Product : BaseObject
{
}
public class Document
{
public string BaseObjectId { get; set; }
}

The only way I see, is to use TPH inheritance (See here for more information).
I have quoted and edited the answer by Erik H.
public enum DocumentType
{
User = 0,
Product = 1
}
public class BaseObject
{
public string Id { get; set; }
public ObjectType DocumentType{ get; set; }
public virtual ICollection<Document> Documents { get; set; }
}
public class User : BaseObject
{
}
public class Product : BaseObject
{
}
public class Document
{
public int Id { get; set; }
public string BaseObjectId { get; set; }
public virtual BaseObject DocumentObject { get; set; }
}
Via fluent-Api you can set a discriminator. This way ef core will only create one table for for both objects Product and User and distinguishes their type by the value of the discriminator column. But only as long as they have exactly the same properties which they share from the base class. As soon as you add properties to one of those subclasses a new table will be created (with all properties from the base- and subclass).
Here is the configuration for the discriminator:
modelBuilder.Entity<BaseObject>()
.HasDiscriminator<DocumentType>("DocumentType")
.HasValue<User>(DocumentType.User)
.HasValue<Product>(DocumentType.Product)
This may not be a clean approach (for me it seems like User and Product should not inherit from the same base class, because they do not share anything than the relations to documents). But it should work as you want it.

You can create a many to many table:
public class Product
{
public string Id { get; set; }
public ICollection<ProductDocument> ProductDocuments{ get; set; }
}
public class Document
{
public string ReferenceId { get; set; }
}
public class ProductDocument
{
public ICollection<Product> Products{ get; set; }
public ICollection<Document> Documents { get; set; }
}
You will have to create a separate table for your user table ie UserDocumentes using the same pattern.

Related

Entity framework core code first : multiple foreign key on itself

We got this exception message when we try to create mutliple foreign key to the owner table (with only one foreign key, there is no problem) :
The dependent side could not be determined for the one-to-one relationship between 'Person.Alternative1Person' and 'Person.Alternative2Person'. To identify the dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship, configure them independently via separate method chains in 'OnModelCreating'. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.
We founded that hading the [ForeignKey] solve the problem. But we don't understand why without this data-annotion it doesn't work, because finally the migration generated code is the same if these foreign key were on another table ?
internal class DatabaseContext : DbContext
{
public DatabaseContext() { }
public DbSet<Country> Country { get; set; }
public DbSet<Resident> Resident { get; set; }
public DbSet<Person> Person { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
string connectionStringSqlServer = #"Server=myserver;Database=TestEf;User Id=x;Password=x;";
optionsBuilder.UseSqlServer(connectionStringSqlServer);
optionsBuilder.EnableSensitiveDataLogging();
optionsBuilder.EnableDetailedErrors();
}
}
}
public class Resident
{
public int Id { get; set; }
public string Name { get; set; }
// Data-annotation ForeignKey not required
public int? HomeCountryId { get; set; }
public virtual Country HomeCountry { get; set; }
// Data-annotation ForeignKey not required
public int? BirthCountryId { get; set; }
public virtual Country BirthCountry { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Alternative1Person")] // Error without this data-annotation if more than one foreign key on itseft
public int? Alternative1PersonId { get; set; }
public virtual Person Alternative1Person { get; set; } constraint)
[ForeignKey("Alternative2Person")] // Error without this data-annotation if more than one foreign key on itseft
public int? Alternative2PersonId { get; set; }
public virtual Person Alternative2Person { get; set; } constraint)
}
Migration generated code are identical, so why the data-annotion is required to avoid the error ?
constraints: table =>
{
table.PrimaryKey("PK_Resident", x => x.Id);
table.ForeignKey(
name: "FK_Resident_Country_BirthCountryId",
column: x => x.BirthCountryId,
principalTable: "Country",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Resident_Country_HomeCountryId",
column: x => x.HomeCountryId,
principalTable: "Country",
principalColumn: "Id");
});
constraints: table =>
{
table.PrimaryKey("PK_Person", x => x.Id);
table.ForeignKey(
name: "FK_Person_Person_Alternative1PersonId",
column: x => x.Alternative1PersonId,
principalTable: "Person",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Person_Person_Alternative2PersonId",
column: x => x.Alternative2PersonId,
principalTable: "Person",
principalColumn: "Id");
});

How to define a hierarchal table using EF core

In the application I am working on, we have a users table, TblUser. Users within this table may belong to a single, parent user. A parent user may have multiple child users.
This relationship is maintained within a table called TblUserMapping with two columns, ParentUserId and ChildUserId corresponding with the parent's and child's TblUser.Id value. TblUser.Id is an auto-incrementing value.
How can I define this within EF Core, and would it be possible to Insert a ChildUser into TblUser and use the auto-generated Id value to also create a TblUserMapping record?
Right now I have:
[Table("TblUser")]
public class TblUser
{
public TblUser()
{
ChildUsers = new List<TblUserMapping>();
}
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<TblUserMapping> ChildUsers { get; set; }
public virtual TblUserMapping ParentUser { get; set; }
}
[Table("TblUserMapping")]
public class TblUserMapping
{
public TblUserMapping()
{
}
public int ChildUserId { get; set; }
public int ParentUserId { get; set; }
public virtual TblUser ChildUser { get; set; }
public virtual TblUser ParentUser { get; set; }
}
public class TblUserMapping : IEntityTypeConfiguration<TblUser>
{
public void Configure(EntityTypeBuilder<TblUser> entity)
{
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.Property(e => e.UserName)
.IsRequired()
.IsUnicode(false);
}
}
public class TblUserMappingMapping : IEntityTypeConfiguration<Entities.TblUserMapping>
{
public void Configure(EntityTypeBuilder<Entities.TblUserMapping> entity)
{
entity.HasKey(e => e.ChildUserId);
entity.Property(e => e.ChildUserId)
.IsRequired();
entity.Property(e => e.ParentUserId)
.IsRequired();
entity.HasOne(e => e.ParentUser)
.WithMany(e => e.ChildUsers)
.HasForeignKey(e => e.ParentUserId);
entity.HasOne(e => e.ChildUser)
.WithOne(e => e.ParentUser)
.HasForeignKey<TblUser>(e => e.Id);
}
}
But this isn't working as I had hoped when I do:
var userInformation = await _context
.Users
.Include(entity => entity.ChildUsers)
.ThenInclude(entity => entity.ChildUser)
.Where(s => s.UserName == userName)
.FirstOrDefaultAsync();
var ChildUser = new TblUser
{
UserName = userModel.UserName,
ParentUser = new TblUserMapping()
{
ParentUser = userInfo
}
};
_context.Users.Add(ChildUser);
await _context.SaveChangesAsync();
You can attach navigation properties, and Entity Framework will populate the ids automatically when it creates them. The example you have given should work, you might need to show us how you are getting userInfo before we can see what's going on.
That being said, instead of keeping a separate mapping table, I would have each child user refer directly to their parent:
[Table("TblUser")]
public class TblUser
{
public int Id { get; set; }
public string UserName { get; set; }
public int? ParentId { get; set; }
public TblUser Parent { get; set; }
// Lazy-loading is not enabled by default in EF Core, so you don't need the 'virtual' keyword
// Also, if the initialization of a member does not depend on constructor arguments, I
// prefer this syntax instead of doing it in the constructor
public ICollection<TblUser> Children { get; set; } = new List<TblUser>();
}
You can use InverseProperty attribute in your model:
[Table("TblUser")]
public class TblUser
{
public TblUser()
{
ChildUsers = new List<TblUserMapping>();
}
public int Id { get; set; }
public string UserName { get; set; }
[InverseProperty("ChildUser")]
public virtual ICollection<TblUserMapping> ChildUsers { get; set; }
[InverseProperty("ParentUser")]
public virtual TblUserMapping ParentUser { get; set; }
}
And in other model:
[Table("TblUserMapping")]
public class TblUserMapping
{
public TblUserMapping()
{
}
public int ChildUserId { get; set; }
public int ParentUserId { get; set; }
[ForeignKey("ChildUserId")]
public virtual TblUser ChildUser { get; set; }
[ForeignKey("ParentUserId")]
public virtual TblUser ParentUser { get; set; }
}
As you see I defined these relations with attributes that means no need to came in your configuration.

Entity Framework - Fluent API - Creating Weird Columns PK : FK FK

My project is Database First and I'm using Entity Framework 6.2.0.
So I have following classes in simple illustration:
Person [1] [n] Link_Table [n] [1] Area
====== ========== ====
ID ID ID
PersonID (FK)
AreaID (FK)
Now when using following code it will through me an inner exception of "invalid column name 'Area2_ID'".
Db_Context db = new Db_Context();
// getting all links with specific "personID"
List<Link_Table> links = db.Link_Table.Where(item => item.PersonID == personID).ToList();
// now getting all areas
List<Area> areas= new List<Area>();
foreach (Link_Table link in links)
{
// ERROR
areas.Add(db.Area.Where(item => item.ID == link.areaID).First());
}
I've already read a little bit about this problem by another users and the problem should be in the (auto-generated) OnModelCreating.
modelBuilder.Entity<Area>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<Area>()
.HasOptional(e => e.Area1)
.WithRequired(e => e.Area2);
For whatever reason using EF in code and creating a new Area-Object, it will show me not only "ID"-Property, but also "Area1"- and "Area2"-Property.
Question
How i have to handle it? The columns "Area1_ID" and "Area2_ID" only exist in EF, not in the database. Can I remove these properties or something else to prevent my exception?
EDIT:
My models:
[Table("Area")]
public partial class Area
{
public Guid ID { get; set; }
[StringLength(40)]
public string Name { get; set; }
[Column(TypeName = "text")]
public string Description{ get; set; }
public virtual Area Area1 { get; set; }
public virtual Area Area2 { get; set; }
}
public partial class Link_Table
{
public Guid ID { get; set; }
public Guid? Person_ID { get; set; }
public Guid? Area_ID { get; set; }
public virtual Person Person{ get; set; }
}
[Table("Person")]
public partial class Person
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Person()
{
Link_Table = new HashSet<Link_Table>();
}
public Guid ID { get; set; }
}
This line looks suspect:
areas.Add(db.Area.Where(item => item.ID == link.areaID).First());
item.ID is the index of the link table record, not an area record.
areas.Add(db.Area.Where(item => item.AreaID == link.areaID).First());
When was the last time you ran a database migration? If your model is correct, and your database is saying there are missing fields, then the database doesn't match the code.
Not very clear for me your goal, but you can refactor your code as follow:
this code:
// now getting all areas
List<Area> areas= new List<Area>();
foreach (Link_Table link in links)
{
// ERROR
areas.Add(db.Area.Where(item => item.ID == link.areaID).First());
}
can be replaced with:
var areas=links.Select(link => link.Area).ToList() // if you decide to add a navigation property
or
var areas=db.Areas.Where(area => links?.Any(link=>link.areaID==area.Id)).ToList();
Most problably the error you get was from .First() for the future use .FirstOrDefault()
Please see below an example of code first implementation:
class Program
{
static void Main(string[] args)
{
var db = new ApplicationDbContext();
var person = new Person();
IQueryable<Link> personLinks = db.Links.Where(x => x.PersonId == person.Id);
List<Area> personAreas = personLinks.GroupBy(x => x.Area).Select(x => x.Key).ToList();
}
}
public class Person
{
public int Id { get; set; }
public ICollection<Link> Links { get; set; }
}
public class Link
{
public int Id { get; set; }
public int PersonId { get; set; }
public Person Person { get; set; }
public int AreaId { get; set; }
public Area Area { get; set; }
}
public class Area
{
public int Id { get; set; }
public ICollection<Link> Links { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<Link> Links { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Link>()
.HasRequired(x => x.Person)
.WithMany(x => x.Links)
.HasForeignKey(x => x.PersonId)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Link>()
.HasRequired(x => x.Area)
.WithMany(x => x.Links)
.HasForeignKey(x => x.AreaId)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}
here you can lear more about entity framework code first follow this link

Entity Framework: Migration falsely adds foreign key column twice

I'm using EntityFramework 6.1.3 with CodeFirst for an Asp.Net application. I have an existing table ("Users") on which I'm trying to add a foreign key "GroupId".
This is the class (Everything with //new are changes made after the last migration)
[Table("Users")]
public class User
{
[Key]
[Column("PK_USER")]
public int Id { get; set; }
[Column("Username")]
public string Username { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Password")]
public string Password { get; set; }
[Column("Firstname")]
public string Firstname { get; set; }
[Column("Lastname")]
public string Lastname { get; set; }
[Column("LastLogin")]
public DateTime? LastLogin { get; set; }
[Column("Department")]
public string Department { get; set; }
[Column("EMail")]
public string EMail { get; set; }
[Column("IsWindowsUser")]
public bool? IsWindowsUser { get; set; }
[Column("Signature")]
public string Signature { get; set; }
[Column("FK_ROLE")]
public int? RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
// new
[Column("GroupId")]
public int? GroupId { get; set; }
//new
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
//new
public virtual ICollection<GroupResponsibility> Responsibilites { get; set; }
public virtual ICollection<UserField> UserFields { get; set; }
public override string ToString()
{
return Username;
}
}
After I run add-migration the following code is generated (omitted other changes)
AddColumn("dbo.Users", "GroupId", c => c.Int());
AddColumn("dbo.Users", "Group_Id", c => c.Int());
CreateIndex("dbo.Users", "GroupId");
CreateIndex("dbo.Users", "Group_Id");
AddForeignKey("dbo.Users", "Group_Id", "dbo.Groups", "Id");
AddForeignKey("dbo.Users", "GroupId", "dbo.Groups", "Id");
As you can see EntityFramework recognized the foreign key but still added a default one "Group_Id". If I go through with it, and update the database, the navigational property "Group" will releate to "Group_Id" instead of the desired "GroupId".
Any ideas what might cause this?
Update 1
I commented out the navigational property and got the same result. Looks like the ICollection Users on the other end of the relation is the culprit. Here is the class "Group"
[Table("Groups")]
public class Group
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int? GroupLeaderId { get; set; }
[ForeignKey("GroupLeaderId")]
public virtual User GroupLeader { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<GroupResponsibility> Responsibilites { get; set; }
public virtual ICollection<ApplicationForm> Applications { get; set; }
public override string ToString()
{
return Name;
}
}
If I comment out the ICollection Users, I get the following exception when adding the migration:
Unable to determine the principal end of an association between the types 'SparePartsDb.Entities.Group' and 'SparePartsDb.Entities.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Update 2
After some googling and changing the Key Attribute on the Group class...
[Key, ForeignKey("GroupLeader")]
public int Id { get; set; }
...I'm able to comment out the ICollection and run the migration. However, GroupId is not not longer recognized as a foreign key even though the navigiational property is present in the class User.
AddColumn("dbo.Users", "GroupId", c => c.Int());
OK, so I've searched for "migration adding duplicate foreign key" in multiple permutations for hours, but I finally figured out what was causing it for me: don't assume Fluent API knows which field you're referring to with WithOne() or WithMany()-- specify the field. See below for details.
I had two entity models in a one-to-many relationship, Address and Invitation, with public virtual ICollection<Invitation> Invitations on Address and public virtual Address Address on Invitation. I chose Fluent API over convention/attributes, so my Invitation builder looked like this:
builder
.HasOne(x => x.Address)
.WithMany()
.HasForeignKey(x => x.AddressId);
Unfortunately, EF Core 2.2 doesn't like having that empty WithMany() in there. Running dotnet ef migrations add InitialCreate resulted in this nonsense, much like OP:
migrationBuilder.CreateTable(
name: "Invitation",
columns: table => new
{
AddressId = table.Column<Guid>(nullable: false),
AddressId1 = table.Column<Guid>(nullable: true),
...
},
constraints: table =>
{
table.PrimaryKey("PK_Invitation", x => x.Id);
table.ForeignKey(
name: "FK_Invitation_Address_AddressId",
column: x => x.AddressId,
principalTable: "Address",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Invitation_Address_AddressId1",
column: x => x.AddressId1,
principalTable: "Address",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
Switching my builder to read:
builder
.HasOne(x => x.Address)
.WithMany(x => x.Invitations)
.HasForeignKey(x => x.AddressId);
fixed the problem for me.
Running dotnet ef migrations remove followed by dotnet ef migrations add InitialCreate again gave me a much nicer migration:
migrationBuilder.CreateTable(
name: "Invitation",
columns: table => new
{
AddressId = table.Column<Guid>(nullable: false),
...
},
constraints: table =>
{
table.PrimaryKey("PK_Invitation", x => x.Id);
table.ForeignKey(
name: "FK_Invitation_Address_AddressId",
column: x => x.AddressId,
principalTable: "Address",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
Hope this helps some other poor soul searching this down.
You shouldn't need to put a
[Column("GroupId")]
on top of the
public int? GroupId { get; set; }
Entity Framework should be able to recognize your mapping by itself.
As stated in msdn:
When generating the database, code first sees the BlogId property in the Post class and recognizes it, by the convention that it matches a class name plus “Id”, as a foreign key to the Blog class. But there is no BlogId property in the blog class. The solution for this is to create a navigation property in the Post and use the Foreign DataAnnotation to help code first understand how to build the relationship between the two classes —using the Post.BlogId property — as well as how to specify constraints in the database.
And the code to this explanation would be:
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime DateCreated { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public Blog Blog { get; set; }
public ICollection<Comment> Comments { get; set; }
}
As you can see, only the complex object has the mapping defining the fk, EF should do the rest for you.
source

EF 6 table mapping error

I'm running into an error trying to save some data in my MVC app. We're using code first.
I'm saving my data like this:
var fieldDefinition = db.CustomFields
.FirstOrDefault(x => x.CustomFieldId == thisResp.CustomFieldId);
var newData = new CustomData
{
ProjectId = new Guid("280288D7-7630-E511-8420-00215E466552"),
CustomFieldId = thisResp.CustomFieldId
};
if (fieldDefinition.AllowMultiple)
{
var values = thisResp.Value.Split(',');
foreach (var thisValue in values)
{
var newMulti = new CustomDataMulti
{
CustomDataId = newData.CustomDataId,
CustomValue = thisValue
};
db.CustomDataMulti.Add(newMulti);
}
}
db.CustomData.Add(newData);
db.SaveChanges();
However, I get this message:
Unable to determine the principal end of the 'PublicationSystem.Model.CustomData_CustomDataMultis' relationship. Multiple added entities may have the same primary key.
My classes are set up like this:
public partial class CustomData : BaseEntity
{
[Key]
public int CustomDataId { get; set; }
public Guid ProjectId { get; set; }
public Guid CustomFieldId { get; set; }
//...
public virtual ICollection<CustomDataText> CustomDataTexts { get; set; }
public virtual ICollection<CustomDataMulti> CustomDataMultis { get; set; }
}
CustomDataMapping.cs
public CustomDataMapping()
{
//Primary key
HasKey(t => t.CustomDataId);
//Constraints
Property(e => e.CustomValue).IsUnicode(false);
HasMany(e => e.CustomDataTexts)
.WithRequired(e => e.CustomData)
.WillCascadeOnDelete(false);
HasMany(e => e.CustomDataMultis)
.WithRequired(e => e.CustomData)
.WillCascadeOnDelete(false);
ToTable("CustomData");
}
CustomDataMulti.cs
[Table("CustomDataMulti")]
public partial class CustomDataMulti : BaseEntity
{
[Key]
public int CustomDataMultiId { get; set; }
public int CustomDataId { get; set; }
[Required]
[StringLength(150)]
public string CustomValue { get; set; }
public virtual CustomData CustomData { get; set; }
}
CustomDataMultiMapping.cs
public CustomDataMultiMapping()
{
//Primary key
HasKey(t => t.CustomDataMultiId);
//Constraints
Property(e => e.CustomValue).IsUnicode(false);
ToTable("CustomDataMulti");
}
I'm not sure what I'm doing wrong.
EntityFramework doesnt understand the principal end of the relationship between the following entities :-
CustomData and CustomDataMulti.
This is because the relationship between the two entities must have one side of the relationship that's constant.
In this case, A CustomData entity can have multiple CustomDataMulti objects. (List).
But can a CustomDataMulti ever exist without belonging to a CustomData object?
What you need to do is change the CustomDataMulti class so that the virtual property for CustomData is Required.
See Below :-
[Table("CustomDataMulti")]
public partial class CustomDataMulti : BaseEntity
{
[Key]
public int CustomDataMultiId { get; set; }
public int CustomDataId { get; set; }
[Required]
[StringLength(150)]
public string CustomValue { get; set; }
[Required]
public virtual CustomData CustomData { get; set; }
}
This is the convention that EntityFramework Uses to determine relationships.
To give a clearer example.
Think of an OrderItem, An OrderItem would always belong to an Order.
An OrderItem without a relevant Order is useless.
The Order entity is the prinicpal end of the relationship.
Hope this helps.

Categories

Resources