Using database-first approach with string primary key and a one-to-many relationship not working in ASP.NET Core Web API - asp.net-core

I have two model classes:
public partial class customer
{
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foreign Key
}
I get an error:
The entity type 'customer' requires a primary key to be defined.
So how it solve?
Datbase table structure

You need to add [Key] attrubute.
public partial class customer
{
[Key]
public string customer_id { get; set; } // Primary Key
public string customer_name { get; set; }
public string course_mobile { get; set; }
public List<customer_address> customer_addresses { get; set; }
}
public partial class customer_address
{
[Key]
public string address_id { get; set; } // Primary Key
public string adreess { get; set; }
public customer customer { get; set; }
public string customer_id { get; set; } // Foriegn Key
}

Related

Object reference not set to an instance of an object in .net core

I have two model class as;
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
}
and
public class MessageModel
{
[Key]
public int messageId { get; set; }
public int senderId { get; set; }
public int customId { get; set; }
public bool ReadInfo { get; set; }
public virtual List<MessageDetailModel> MessageDetails { get; set; }
}
and it is my context class ;
public virtual DbSet<MessageDetailModel> messageDetails { get; set; }
public virtual DbSet<MessageModel> messages { get; set; }
public virtual DbSet<PersonModel> persons { get; set; }
public virtual DbSet<DirectoryModel> directory { get; set; }
I am trying to get messageId over MessageDetailModel but messageId returns as 0 and I have that error "Object reference not set to an instance of an object"
Console.WriteLine(k.messageModel.messageId); //( k is my var which gets from messagedetail model)
How can ı reach messageId over MessadeDetailModel
There is no current link between your two models that would represent a Foreign Key.
You'd need to do something like this for your model if you want a Foreign Key to link to the related object:
public class MessageDetailModel
{
[Key]
public int messageDetailsId { get; set; }
[ForeignKey("messageId")] // Added Data Annotation for the Foreign Key relationship
public MessageModel messageModel { get; set; }
public string detail { get; set; }
public int senderId { get; set; }
public int customerId { get; set; }
public string phone { get; set; }
public DateTime date { get; set; }
public int messageId { get; set; } // This would be your Foreign Key
}
I've added the messageId column to your MessageDetailModel to match the Primary Key column of your MessageModel as that's necessary for the link to form.
You would use the [ForeignKey("messageId")] Data Annotation above the variable for the MessageModel to determine what value it needs to use when finding the object you want.

EntityFramework Trying to create multiple links to the same table, FK Constraint error

I have a table called DeliveryRequest and another table called Operator, table DeliveryRequest is as follows:
public class DeliveryRequest
{
public int ID { get; set; }
public DateTime Date { get; set; }
public string UserID { get; set; }
public string Waybill { get; set; }
public string Reference { get; set; }
public int SupplierID { get; set; }
public Supplier Supplier { get; set; }
//[ForeignKey("Operator")]
public int SenderID { get; set; }
public Operator Sender { get; set; }
//[ForeignKey("Operator")]
public int ReceiverID { get; set; }
public Operator Receiver { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public int ServiceID { get; set; }
public Service Service { get; set; }
}
And table Operator is as follows:
public class Operator
{
public int ID { get; set; }
public string Company { get; set; }
public int ContactID { get; set; }
public Contact Contact { get; set; }
public int AddressID { get; set; }
public Address Address { get; set; }
}
So the problem is, when I am trying to update my database I get a FK Constraint error as follows:
Introducing FOREIGN KEY constraint
'FK_dbo.DeliveryRequests_dbo.Operators_SenderID' on table
'DeliveryRequests' 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.
And the previous error is the same. As follows:
System.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN
KEY constraint 'FK_dbo.DeliveryRequests_dbo.Operators_SenderID' on
table 'DeliveryRequests' may cause cycles or multiple cascade paths.
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
FOREIGN KEY constraints.
Focus on the Sender and Receiver part, I am no expert but the error must be there lol
//[ForeignKey("Operator")]
public int SenderID { get; set; }
public Operator Sender { get; set; }
//[ForeignKey("Operator")]
public int ReceiverID { get; set; }
public Operator Receiver { get; set; }
It looks like you are using Code First approach. So try to turn off CascadeDelete for DeliveryRequests:
modelBuilder.Entity<DeliveryRequests>()
.HasRequired(c => c.Operator )
.WithMany()
.WillCascadeOnDelete(false);
For example:
public class YourDBContext: DbContext
{
public YourDBContext(): base()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DeliveryRequests>()
.HasRequired(c => c.Operator )
.WithMany()
.WillCascadeOnDelete(false);
}
}

EF CORE 2.0 Incompatible relationship (nullable foreign key)

In our businessslogic we have some contacts row that may have a relationship with one billing row (0..N).
Here the contact class
public class ESUsersContact
{
[Key]
public int Id { get; set; }
[ForeignKey("Billing")]
public int? BillingId { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Phone { get; set; }
public string CellPhone { get; set; }
public string Fax { get; set; }
public ES.Enums.BusinessESCommon.Language.AllLanguage Language { get; set; }
public virtual ICollection<ESUsersCompany> Companies { get; set; }
public virtual ESUsersBilling Billing { get; set; }
}
Here is the billing class
[Key, Column(Order = 0)]
[ForeignKey("Company")]
public int CompanyId { get; set; }
[Key, Column(Order = 1)]
public ES.Enums.BusinessESUsers.Billing.Type Type { get; set; }
public ES.Enums.BusinessESUsers.Billing.Payment PaymentType { get; set; }
public ES.Enums.BusinessESUsers.Billing.Frequency PaymentFrequency { get; set; }
public decimal Amount { get; set; }
public bool IsFreeTrial { get; set; }
public DateTime FreeTrialEndDate { get; set; }
public DateTime? NextPaymentDate { get; set; }
public virtual ESUsersCompany Company { get; set; }
public virtual ICollection<ESUsersContact> Contacts { get; set; }
}
However, I receive this error doing so.
The relationship from 'ESUsersContact.Billing' to 'ESUsersBilling.Contacts' with foreign key properties {'BillingId' : Nullable<int>} cannot target the primary key {'CompanyId' : int, 'Type' : Type} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.
I don't understand why the error occurs and state the primary key {'CompanyId' : int, 'Type' : Type}.
ESUsersContact.Billing class has a composite key. ESUsersContact has to map both of the foreign keys. CompanyId and Type. You can not refer only one column since ESUsersContact.Billing has two columns for the key.

Is it possible to create a Domain Class which has Multiple FK Columns to same PK?

I'm a newbie to designing database.
I have problem how to define a domain class which has multiple foreign keys linked with a same primary key.
Here is my model:
namespace OceanFmsSystem.Domain
{
public class ExportTemplate
{
public int Id { get; set; }
public List<ExportBooking> ExportBookings { get; set; }
public string TemplateName { get; set; }
public int CustomerId { get; set; }
public string Incoterms { get; set; }
public string IncotermsDetail { get; set; }
public string PaymentTerm{ get; set; }
public int CountryOriginId { get; set; }
public int CountryDestinationId { get; set; }
}
}
What I want to do is that CountryOriginId & CountryDestinationId should refer to the below class as foreign keys:
namespace OceanFmsSystem.Domain
{
public class Country
{
public int Id { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
}
As far as I know, in EF Core there is an convention which I should name a foreign key as below for migration from code to database.
public type ClassNameOfPrimaryKeyId { get; set;}
Is there any possible way to make this happens?
Yes, possible. Your class should look like this:
public class ExportTemplate
{
//...
public int CountryOriginId { get; set; }
public Country CountryOrigin { get; set; }
public int CountryDestinationId { get; set; }
public Country CountryDestination { get; set; }
}
EF is smart enough to figure the Ids by convention. If you do not wish to follow the convention you can use [ForeignKey] attribute on the properties to configure the FK:
[ForeignKey("Origin")]
public int MyOriginId { get; set; }
public Country Origin { get; set; }

How to set one foreign key references multiple primary keys in EF

I use code-first approach. I want to use just ObjectId property in ObjectScore as foreign key for three relations with Professor (Id) , College (Id) and EducationalGroup (Id), like what's happening at SQL
CONSTRAINT [FK_ObjectScore_Colege] FOREIGN KEY([ObjectId])
CONSTRAINT [FK_ObjectScore_Professer] FOREIGN KEY([ObjectId])
CONSTRAINT [FK_ObjectScore_EducationGroup] FOREIGN KEY([ObjectId])
How to make this relation in Entity Framework (data annotations or fluent api)?
Thanks all
public class Professor : Person
{
public int ProfessorCode { get; set; }
public virtual ICollection<EducationalGroup> EducationalGroups { get; set; }
public virtual ICollection<College> Colleges { get; set; }
public virtual ICollection<ObjectScore> ObjectScores { get; set; }
}
public class College : BaseClass
{
public int CollegeCode { get; set; }
public virtual ICollection<Professor> Professors { get; set; }
public virtual ICollection<EducationalGroup> EducationalGroups { get; set; }
public virtual ICollection<ObjectScore> ObjectScores { get; set; }
}
public class EducationalGroup : BaseClass
{
public int CollegeCode { get; set; }
public virtual ICollection<Professor> Professors { get; set; }
public virtual College College { get; set; }
public virtual ICollection<ObjectScore> ObjectScores { get; set; }
}
public class ObjectScore
{
public Guid Id { get; set; }
public int CurrentScore { get; set; }
public virtual Term Term { get; set; }
public virtual Score Score { get; set; }
public int ObjectId { get; set; }
}
and my BaseClass and Person classes:
public class Person : BaseClass
{
public string Family { get; set; }
}
public class BaseClass
{
public BaseClass()
{
IsActive = false;
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime? CreationDate { get; set; }
public DateTime? LastModifiedDate { get; set; }
public bool IsActive { get; set; }
}