Optional 1:1 relationship in Entity Framework Code First - c#

I'm trying to create what I think would be either called an optional 1:1 or possibly 0..1:0..1 relationship in Entity Framework. I want to be able to have navigation properties on both objects.
I am using Entity Framework's Fluent API over an existing database schema.
For simplicity, lets assume the following tables:
Car
Id int not null
Driver
Id int not null
CarId int null unique
Using the following classes:
public class Car
{
public int Id { get; set; }
public virtual Driver { get; set; }
}
public class Driver
{
public int Id { get; set; }
public virtual Car { get; set; }
}
The idea is a Car and a Driver can exist independent of one another, but when a Driver gets associated with a Car it is a mutually exclusive association: the Driver can only be associated with that Car and that Car can only be associated to that Driver.
I tried the following fluent configuration:
Inside Driver's Configuration:
HasOptional(d => d.Car)
.WithOptionalDependent()
.Map(d => d.MapKey("CarId"));
And inside the Car configuration
HasOptional(c => cDriver)
.WithOptionalPrincipal()
.Map(d => d.MapKey("CarId"));
When I try this I get the following:
Schema specified is not valid. Errors:
(203,6) : error 0019: Each property name in a type must be unique. Property name 'CarId' was already defined.
Is there a way to model this scenario with navigation properties on both objects in Entity Framework?

You don't need to set it up in both fluent classes. I'm surprised that is the error that you received, and not that the relationship is already set up.
Your Drive class will need the CarId as part of the class:
public class Driver
{
public int Id { get; set; }
// Make this int? if a Driver can exist without a Car
public int CarId { get; set; }
public virtual Car { get; set; }
}
Then you just need this in the Fluent Config file for Driver, and nothing in the one for Car.
HasOptional(d => d.Car)
.WithOptionalDependent()
.Map(d => d.MapKey("CarId"));

You can do this without Fluent API:
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public int? DriverId { get; set; }
[ForeignKey("DriverId")]
public virtual Driver Driver { get; set; }
}
public class Driver
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Car> Cars { get; set; }
}
Then you need to check if the Driver already has a car, to guarantee that he can have only one.

Related

The "Guid" type must be a reference type to be used as a "TRelatedEntity" parameter in the generic type or method

I have the class ArticleEntity
public class ArticleEntity
{
public Guid ArticleID { get; set; }
public Guid AuthorID {get; set;}
public BaseWriter Author { get; set; }
public string Titulo { get; set; }
public string Decricao { get; set; }
public List<Tag> Tags { get; set; }
public ArticleStatus Status { get; set; }
public DateTime PublishedOn { get; set; }
public Admin ApprovedBy { get; set;}
public DateTime RemovedOn { get; set;}
public Admin DeletedBy { get; set;}
}
And BaseWriter, which is an abstract class that's inherited by the Admin class. So far Admin has nothing else implemented
public abstract class BaseWriter
{
public Guid Id { get; set; }
public string Nome { get; set; }
public string Matricula { get; set; }
public List<ArticleEntity> AllArticles { get; set; }
public WriterProfile Profile { get; set; }
}
And I'm trying to map it, using the HasOne method to configure two properties to become the primary key
public class ArticleMap : IEntityTypeConfiguration<ArticleEntity>
{
public void Configure(EntityTypeBuilder<ArticleEntity> builder)
{
builder.ToTable("Article");
builder.HasKey(u => u.ArticleID);
builder.HasOne(u => u.Author);
builder.HasOne(u => u.AuthorID);
}
}
But the problem is that, in the Configure function I'm getting this error message about the AuthorID
The type "Guid" must be a reference type in order to use it as parameter TRelatedEntity in the generic type or method "EntityTypeBuilder.HasOne(Expression<Func<ArticleEntity, TRelatedEntity>>)",
What's the reason of this message? I'd like to have UserName(string) and UserID(Guid) as primary keys of Article. I'm new in C# and Entity, so I'd appreciate any help. Thanks!
What you are using is called Fluent API, and it is part of EntityFramework. This will help you find information easier as you now know what to look for.
As for your issue, the HasOne function must point towards a reference Type like a class or anything that can be used as an table. And because baseWriter can be a table it can be used in this context. Whereas ArticleID is struct and doesn't have properties.
Fluent API has a unique way of doing things. You describe the relationships fluently, all within one sentence/function so to say.
Let's look at what your code should look like:
builder.HasOne(u => u.Author) // Define the ArticleEntity to BaseWriter relationship
.WithMany( u => u.AllArticles) // Define the baseWriter to ArticleEntity relationship
.HasForeignKey (u => u.AuthorID); // Describe what foreign key the baseWriter refers to.

How can I create working lists and save them using the Entity Framework Core and ASP.NET Web API?

I am making a web app similar to google classroom in that you can join classes.
I have a class "Account" and inside that account I have a list that should hold the IDs of all the classes the account has joined. I tried to make the list a list of longs, but I couldn't do that because I got the error:
System.InvalidOperationException: 'The property
'Account._classesJoined' could not be mapped, because it is of type
'List' which is not a supported primitive type or a valid entity
type. Either explicitly map this property, or ignore it using the
'[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
'OnModelCreating'.
The way I solved this problem is to create a class "JoinedClassId" to make a list of instead, with a property "classIdNumber". However, during testing, I noticed that the JoinedClassIds that I added to the the Account object were not saving. I think this is because I am not saving the database table for the JoinedClassId class.
Do I have to create a database context and controller for the JoinedClassId class? I don't want to be able to manipulate the JoinedClassId class from the API, I'm only using it as a data container. Is there a way I could either create a long list and save it or save the JoinedClassIds?
In EF Core "Many-to-many relationships without an entity class to represent the join table are not yet supported".
Book -> Category has many-to-may rel so this should create the 3 tables in DB :
Books, Category and BookCategory
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
//public ICollection<Category> Categories { get; set; } // cannot appear
// For the many-to-many rel
public List<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
//public ICollection<Book> Books { get; set; } // cannot appear
// For the many-to-many rel
public List<BookCategory> BookCategories { get; set; }
}
// Class because of the many-to-many rel
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class MyContextDbContext : DbContext
{
public MyContextDbContext(DbContextOptions<MyContextDbContext> dbContextOptions)
: base(dbContextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookCategory>()
.HasKey(t => new { t.BookId, t.CategoryId });
modelBuilder.Entity<BookCategory>()
.HasOne(bctg => bctg.Book)
.WithMany(ctg => ctg.BookCategories)
.HasForeignKey(book => book.CategoryId);
modelBuilder.Entity<BookCategory>()
.HasOne(bctg => bctg.Category)
.WithMany(ctg => ctg.BookCategories)
.HasForeignKey(ctg => ctg.BookId);
}
public DbSet<Book> Book { get; set; }
public DbSet<Category> Category { get; set; }
}

Multiple one-to-one relationship with two independent tables and one dependent

I have read a lot of related questions about this topic but none of them seemed to address my problem, so please bear with me.
I am new to EF and trying to establish the following relationship, in ASP .NET MVC, using EF6:
I need to have two permanent tables, Drivers and Cars. I now need to create a relationship between these tables when a Driver is associated to a Car. But one Driver can only be assigned to one Car.
A Driver may not always be associated to a Car and vice-versa and I want to maintain both tables even if there isn't always an association between them, so that is why I believe I need to have an additional table exclusively to make this connection. Which I think will create a 1:1:1 relationship between these classes.
Below is the model for my POCO classes.
Models
public class Driver
{
public int DriverID { get; set; }
public string Name { get; set; }
//other additional fields
public DriverCar DriverCar { get; set; }
}
public class Car
{
public int CarID { get; set; }
public string Brand { get; set; }
//other additional fields
public DriverCar DriverCar { get; set; }
}
public class DriverCar
{
public int DriverCarID { get; set; }
public int DriverID { get; set; }
public Driver Driver { get; set; }
public int CarID { get; set; }
public Car Car { get; set; }
}
I have tried configuration the relationships using Fluent API but I believe I am doing it completly wrong since I have got errors such as:
Introducing FOREIGN KEY constraint 'FK_dbo.DriverCar_dbo.Car_CarId' on
table 'DriverCar' may cause cycles or multiple cascade paths. Specify
ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
KEY constraints. Could not create constraint or index. See previous
errors.
Fluent Api
modelBuilder.Entity<DriverCar>()
.HasRequired(a => a.Driver)
.WithOptional(s => s.DriverCar)
.WillCascadeOnDelete(false);
modelBuilder.Entity<DriverCar>()
.HasRequired(a => a.Car)
.WithOptional(s => s.DriverCar)
.WillCascadeOnDelete(false);
I am really not sure if I am missing something or if there is some better approach to handle this situation and I would appreciate so much if someone can give me some feedback on how to solve this.
Update
Just found an interesting answer here: Is it possible to capture a 0..1 to 0..1 relationship in Entity Framework?
Which I believe is exactly what I want: a 0..1 to 0..1 relationship. But all the mentioned options seem too complex and I'm not quite sure which one is the best or how to even correctly implement them.
Are these type of relationships supposed to be so hard to implement in EF?
For example, I tried Option 1 but it created a 0..1 to many relationship from both tables - Driver to Car and Car to Driver. How am I suppose to create an unique association between them then?
Try this for your models. Virtual enables lazy loading and is advised for navigation properties. DataAnnotations showing the Foreign Keys (or use fluent) to be sure each relationship is using the correct key.
public class Driver
{
public int DriverID { get; set; }
public string Name { get; set; }
//other additional fields
public DriverCar? DriverCar { get; set; }
}
public class Car
{
public int CarID { get; set; }
public string Brand { get; set; }
//other additional fields
public DriverCar? DriverCar { get; set; }
}
public class DriverCar
{
public int DriverCarID { get; set; }
[ForeignKey("Driver")]
public int DriverID { get; set; }
public Driver Driver { get; set; }
[ForeignKey("Car")]
public int CarID { get; set; }
public Car Car { get; set; }
}
modelBuilder.Entity<Driver>()
.HasOptional(a => a.DriverCar)
.WithRequired(s => s.Driver)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Car>()
.HasOptional(a => a.DriverCar)
.WithRequired(s => s.Car)
.WillCascadeOnDelete(false);
Note: Changed to Data Annotations for Foreign Keys. Inverted fluent statements. Fixed Driver to Car in second relationship.
Here is a simple way to create a one to zero. Note that I'm a fan of keeping the Id of all tables as just Id, not CarId etc, just my style. This is just a console app so once you add the EF nuget you could just copy/paste.
But the below code works with .net framework 4.6 and EF6.2 It creates the following tables
Car
Id (PK, int, not null)
Driver_Id (FK, int, null)
Driver
Id (PK, int, not null)
Under this schema a Car can have only one driver. A driver may still drive multiple cars though. I'm not sure if that's an issue for you or not.
using System.Data.Entity;
namespace EFTest
{
class Program
{
static void Main(string[] args)
{
var connectionString = "<your connection string>";
var context = new DatabaseContext(connectionString);
var car = new Car();
var driver = new Driver();
context.Cars.Add(car);
context.Drivers.Add(driver);
car.Driver = driver;
context.SaveChanges();
}
}
public class Car
{
public int Id { get; set; }
public virtual Driver Driver { get; set; }
}
public class Driver
{
public int Id { get; set; }
}
public class DatabaseContext : DbContext, IDatabaseContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<Driver> Drivers { get; set; }
public DatabaseContext(string connectionString) : base(connectionString){ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasKey(n => n.Id)
.HasOptional(n => n.Driver);
modelBuilder.Entity<Driver>()
.HasKey(n => n.Id);
}
}
}
But if you REALLY wanted to enforce the constraint of only one mapping per car and driver, you could do it with the code below. Note that when you have the joining entity, you don't put it's Id anywhere on the joined entities.
using System.Data.Entity;
namespace EFTest
{
class Program
{
static void Main(string[] args)
{
var connectionString = "your connection string";
var context = new DatabaseContext(connectionString);
//Create a car, a driver, and assign them
var car = new Car();
var driver = new Driver();
context.Cars.Add(car);
context.Drivers.Add(driver);
context.SaveChanges();
var assignment = new DriverAssignment() { Car_id = car.Id, Driver_Id = driver.Id };
context.DriverAssignments.Add(assignment);
context.SaveChanges();
//Create a new car and a new assignment
var dupCar = new Car();
context.Cars.Add(dupCar);
context.SaveChanges();
var dupAssignment = new DriverAssignment() { Car_id = dupCar.Id, Driver_Id = driver.Id };
context.DriverAssignments.Add(dupAssignment);
//This will throw an exception because it will violate the unique index for driver. It would work the same for car.
context.SaveChanges();
}
}
public class Car
{
public int Id { get; set; }
}
public class Driver
{
public int Id { get; set; }
}
public class DriverAssignment
{
public int Car_id { get; set; }
public int Driver_Id { get; set; }
}
public class DatabaseContext : DbContext, IDatabaseContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<Driver> Drivers { get; set; }
public DbSet<DriverAssignment> DriverAssignments { get; set; }
public DatabaseContext(string connectionString) : base(connectionString) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>().HasKey(n => n.Id);
modelBuilder.Entity<Driver>().HasKey(n => n.Id);
modelBuilder.Entity<DriverAssignment>().HasKey(n => new { n.Car_id, n.Driver_Id });
modelBuilder.Entity<DriverAssignment>().HasIndex(n => n.Car_id).IsUnique();
modelBuilder.Entity<DriverAssignment>().HasIndex(n => n.Driver_Id).IsUnique();
}
}
}

Entity Framework Code First One Property of Class and List of The Same Class

I'm using entity framework code first approach
I have a class
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public Person Director { get; set; }
public virtual ICollection<Person> Actors { get; set; }
}
and a class
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
When the database is created I get one table Movies with Id, Title, Director_Id and a table Person with Id and Name.
I expect to have a table Movies_Persons with columns Movie_Id and Actor_Id
How can I achieve this?
Your Problem is, that you don`t tell the Person Class, that there can be multiple Movies per person.
So by adding the following line in your person class:
public virtual ICollection<Movie> Movies { get; set; }
Your entity knows that both your classes can have multiple references to the other class.
To fulfill this requirement Entity Framework will create a third table with Movie_ID and Person_ID.
If you want more informations just look for:
Entity Framework - Many to many relationship
or follow this link:
http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
You can check out the other articels on that page too, if you are new to entity framework.
UPDATE:
Sorry i missed, that you are already have another reference to your person table.
Here you have to tell your entity framework, which way you want to reference the two tables by fluent api.
Check out this stackoverflow answer. That should do the trick.
You have to insert this code into your OnModelCreating Function of your DbContext Class.
So your final code should look like this:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public virtual Person Director { get; set; }
public virtual ICollection<Person> Actors { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Movie> Movies_Actors { get; set; }
public virtual ICollection<Movie> Movies_Directors { get; set; }
}
And in your OnModelCreating add following code:
modelBuilder.Entity<Movie>()
.HasMany(a => a.Actors)
.WithMany(a => a.Movies_Actors)
.Map(x =>
{
x.MapLeftKey("Movie_ID");
x.MapRightKey("Person_ID");
x.ToTable("Movie_Actor");
});
modelBuilder.Entity<Movie>()
.HasRequired<Person>(s => s.Director)
.WithMany(s => s.Movies_Directors);
I don't have the possibility to test the code, but that should do the trick.
If you have to do some adjustments to make it work, plz add them in the comments, so other ppl can benefit from it.

EF Foreign Key using Fluent API

Here are my models. I have one to one mapping for Vehicle and Driver. I will have the vehicle created first and then map the driver to the vehicle.
public class Driver
{
public int Id { get; set; }
public String Name { get; set; }
public int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public String Name { get; set; }
public virtual Driver Driver { get; set; }
public int VehicleGroupId { get; set; }
public virtual VehicleGroup Vehicles { get; set; }
}
I want to use VehicleId property in Driver class to keep id of vehicle the driver is driving.
I've written the following Fluent API code:
modelBuilder.Entity<Vehicle>()
.HasRequired(d => d.Driver)
.WithRequiredPrincipal();
But it creates a new column in Drivers table - Vehicle_VehicleId and maps it to the VehicleId on Vehicle table. I want the VehicleId of Driver table to map.
Also, i'm brand new to EF and Fluent API. I find it extremely confusing choosing between WithRequiredDependent and WithRequiredPrincipal. Would be glad if you can describe it in simple words. Thanks.
This line:
public int VehicleId { get; set; }
is telling EF, through code-conventions, that you want a foreign key in Driver pointing to Vehicle.
The following is telling EF that you want a 1:1 relationship from Driver to Vehicle:
public virtual Vehicle Vehicle { get; set; }
You should remove both and stick with your Fluent API configuration.
Regarding WithRequiredPrincipal vs. WithRequiredDependent:
You are specifying a compulsory relationship between Vehicle and Driver, with navigation from Vehicleto Driver, thus: Vehicle 1 --> 1 Driver
(Vehicle is the principal and Driver the dependent, since the navigation property is located in Vehicleand pointing to Driver .)
modelBuilder.Entity<Vehicle>()
.HasRequired(d => d.Driver)
.WithRequiredDependent();
You are specifying a compulsory relationship between Vehicle and Driver, with navigation from Driver to Vehicle, thus: Vehicle 1 <-- 1 Driver
(Vehicle is the dependent and Driver the principal, since the navigation property is located in Driver pointing to Vehicle.)
These two are analogous:
modelBuilder.Entity<Vehicle>()
.HasRequired(v => v.Driver)
.WithRequiredPrincipal();
modelBuilder.Entity<Driver>()
.HasRequired(d => d.Vehicle)
.WithRequiredDependent();
EF creates the Vehicle_VehicleId column because you have VehicleId and Vehicle on your Driver Entity.
Remove VehicleId and Vehicle from your Driver Entity:
public class Driver
{
public int Id { get; set; }
public String Name { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public String Name { get; set; }
}
Using:
modelBuilder.Entity<Vehicle>()
.HasRequired(d => d.Driver)
.WithRequiredPrincipal();
you are setting the relationship so no need to include manual properties in your entity classes.
You get the VehicleId from the navigation property Vehicle:
IQueryable<int> vehicleIds = context.Drivers.Select(x => x.Id == 123).Vehicles.Id;

Categories

Resources