Entity Framework one to one relation, disconnected entities - entity-framework

I want to work with disconnected objects. In my model a user can have or not an address.
First my model:
public class ApplicationUser : IdentityUser, IUser
{
public ApplicationUser() : base()
{
}
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual DateTime BornDate { get; set; }
public virtual SubscriptionSetting SubscriptionSetting { get; set; }
public virtual Address Address { get; private set; }
public void AddAddress(Address address)
{
this.Address = address;
}
}
public class Address
{
public Address(string id, string number, string type, string nom, string postalCode, string city, GPSCoordinates gps)
{
this.Id = id;
this.Number = number;
this.Type = type;
this.Nom = nom;
this.PostalCode = postalCode;
this.City = city;
this.GPSCoordinates = gps;
}
public virtual string Id { get; set; }
public virtual string Number { get; set; }
public virtual string Type { get; set; }
public virtual string Nom { get; set; }
public virtual string PostalCode { get; set; }
public virtual string City { get; set; }
public virtual GPSCoordinates GPSCoordinates { get; set; }
}
My context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection")
{
this.Database.Log = Console.Write;
}
public DbSet<Address> Addresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new SubscriptionSettingConfiguration());
modelBuilder.Configurations.Add(new ApplicationUserConfiguration());
modelBuilder.Configurations.Add(new AddressConfiguration());
base.OnModelCreating(modelBuilder);
}
}
My configuration:
public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
public ApplicationUserConfiguration() : base()
{
HasRequired(u => u.Address).WithRequiredPrincipal();
Property(u => u.BornDate).HasColumnType("datetime2");
}
}
public class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
HasKey(m => m.Id);
}
}
And my repo:
public virtual async Task<TEntity> InsertAsync(TEntity entity)
{
DbSet.Add(entity);
try
{
await _dbContext.SaveChangesAsync();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
);
}
return entity;
}
Finally my unit test :
public class adress_repository_test
{
IRepository<Address> _addressRepository;
DbContext _context;
public adress_repository_test()
{
_context = new ApplicationDbContext();
_addressRepository = new Repository<Address>(_context);
}
[Fact]
public async Task insert_new_address_success()
{
GPSCoordinates gps = new GPSCoordinates(44.5, 41.2);
Address address = new Address("d0ead995-ca31-4950-bfd3-93e0ca82e37e", "BATC", "Allée", "beethoven", "60100", "creil", gps);
var result = await _addressRepository.InsertAsync(address);
Assert.NotEmpty(address.Id);
}
When the test run it throws an exception :
Violation of PRIMARY KEY constraint 'PK_dbo.Address'. Cannot insert
duplicate key in object 'dbo.Address'. The duplicate key value is
(d0ead995-ca31-4950-bfd3-93e0ca82e37e)

Sorry for this question but i haven't becareful about the config of my test, the connexion string is not present, and it's create a new database .
Steve is right the row is present in the BDD

Related

Is there any change when upgrading .Net 6 to .Net 7 in database migrations?

I am using the Npgsql driver and after upgrading all dependencies to version 7.0.0, I cannot fulfill any migration. I am doing some seeding in DbContext.
This is my context:
public class TransportationContext: DbContext
{
public DbSet<Gender> Genders { get; set; } = null!;
public DbSet<Language> Languages { get; set; } = null!;
public DbSet<Region> Regions { get; set; } = null!;
public DbSet<Role> Roles { get; set; } = null!;
public DbSet<Policy> Policies { get; set; } = null!;
public DbSet<User> Users { get; set; } = null!;
public DbSet<Servant> Servants { get; set; } = null!;
public DbSet<Vehicle> Vehicles { get; set; } = null!;
public DbSet<DiscountCode> DiscountCodes { get; set; } = null!;
public DbSet<DiscountCodeUser> DiscountCodeUsers { get; set; } = null!;
public DbSet<Service> Services { get; set; } = null!;
public DbSet<ServiceBaseType> ServiceBaseTypes { get; set; } = null!;
public DbSet<ServiceAreaType> ServiceAreaTypes { get; set; } = null!;
public DbSet<ServiceAreaParams> ServiceAreaParams { get; set; } = null!;
public DbSet<BaseNightPeriods> BaseNightPeriods { get; set; } = null!;
public DbSet<ServantStatus> ServantStatuses { get; set; } = null!;
public DbSet<Tasks> Tasks { get; set; } = null!;
public DbSet<ServantDailyStatistic> ServantDailyStatistics { get; set; } = null!;
public DbSet<CanceledTask> CanceledTasks { get; set; } = null!;
public DbSet<CancelReason> CancelReasons { get; set; } = null!;
public DbSet<CancelReasonTranslation> CancelReasonTranslations { get; set; } = null!;
public DbSet<Request> Requests { get; set; } = null!;
public DbSet<RequestServant> RequestServants { get; set; } = null!;
public DbSet<Group> Groups { get; set; } = null!;
public DbSet<ServantDailyOnlinePeriod> ServantDailyOnlinePeriods { get; set; } = null!;
public DbSet<ServantHourlyStatistic> ServantHourlyStatistics { get; set; } = null!;
public DbSet<TaskHourlyStatistic> TaskHourlyStatistics { get; set; } = null!;
public DbSet<DailyStatistic> DailyStatistics { get; set; } = null!;
public DbSet<ActiveRole> ActiveRoles { get; set; } = null!;
[Obsolete("Obsolete")]
static TransportationContext()
{
NpgsqlConnection.GlobalTypeMapper.MapEnum<DiscountCodeTypeEnum>();
NpgsqlConnection.GlobalTypeMapper.MapEnum<TaskStatusEnum>();
NpgsqlConnection.GlobalTypeMapper.MapEnum<RequestTypeEnum>();
NpgsqlConnection.GlobalTypeMapper.MapEnum<RequestStatusEnum>();
}
public TransportationContext(DbContextOptions<TransportationContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(o => o.UseNetTopologySuite());
// optionsBuilder.ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresExtension("postgis");
modelBuilder.HasPostgresEnum<DiscountCodeTypeEnum>();
modelBuilder.HasPostgresEnum<TaskStatusEnum>();
modelBuilder.HasPostgresEnum<RequestTypeEnum>();
modelBuilder.HasPostgresEnum<RequestStatusEnum>();
modelBuilder.Entity<Policy>().HasData(GetPolicies());
modelBuilder.Entity<Role>().HasData(GetBaseRoles());
modelBuilder
.Entity<Policy>()
.HasMany(p => p.Roles)
.WithMany(r => r.Policies)
.UsingEntity(j => j.HasData(GetRolePolicies(1)));
modelBuilder.Entity<DiscountPeriods>(builder =>
{
// StartTime is a TimeOnly property and time on database
builder.Property(x => x.StartTime)
.HasConversion<TimeOnlyConverter, TimeOnlyComparer>();
// EndTime is a TimeOnly property and time on database
builder.Property(x => x.EndTime)
.HasConversion<TimeOnlyConverter, TimeOnlyComparer>();
});
modelBuilder.Entity<ServantDailyStatistic>(builder =>
{
// StartTime is a TimeOnly property and time on database
builder.Property(x => x.Date)
.HasConversion<DateOnlyConverter, DateOnlyComparer>();
});
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
//If the actual entity is an auditable type.
if (typeof(Auditable).IsAssignableFrom(entityType.ClrType))
{
//This adds (In a reflection type way), a Global Query Filter
//https://docs.microsoft.com/en-us/ef/core/querying/filters
//That always excludes deleted items. You can opt out by using dbSet.IgnoreQueryFilters()
var parameter = Expression.Parameter(entityType.ClrType, "p");
var deletedCheck =
Expression.Lambda(
Expression.Equal(Expression.Property(parameter, "DeletedAt"), Expression.Constant(null)),
parameter);
modelBuilder.Entity(entityType.ClrType).HasQueryFilter(deletedCheck);
}
}
public async Task<int> SaveChangesAsync()
{
AddTimestamps();
return await base.SaveChangesAsync();
}
}
I want to add this property in migration
public class RequestServant : Auditable
{
public int Id { get; set; }
> public bool IsOnline {get; set; }
public int RequestId { get; set; }
public int ServantId { get; set; }
This gives me an error every time:
System.ArgumentException: An item with the same key has already been added. Key: CreatedAt
at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.AddSeedData(IEntityType entityType, Dictionary`2 identityMaps, EntityState initialState)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.TrackData(IRelationalModel source, IRelationalModel target, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDataOperations(IRelationalModel source, IRelationalModel target, DiffContext diffContext)+MoveNext()
at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IRelationalModel source, IRelationalModel target)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
An item with the same key has already been added. Key: CreatedAt
Here are the other data context methods for data seeding and global query filter:
private static IEnumerable<Policy> GetPolicies()
{
var allPolicies = Enum.GetValues<PolicyEnum>();
return allPolicies.Select(p => new Policy { Id = (int)p, Name = p.ToString() });
}
private static IEnumerable<Policy> GetBaseRoles()
{
var allPolicies = Enum.GetValues<BaseRoles>();
return allPolicies.Select(p => new Policy { Id = (int)p, Name = p.ToString() });
}
private static IEnumerable<object> GetRolePolicies(int roleId)
{
var allPolicies = Enum.GetValues<PolicyEnum>();
return allPolicies.Select(p => new { PoliciesId = (int)p, RolesId = roleId });
}
private void AddTimestamps()
{
var entities = ChangeTracker.Entries()
.Where(x => x.Entity is Auditable && (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach (var entity in entities)
{
var now = DateTime.UtcNow; // current datetime
if (entity.State == EntityState.Added)
{
((Auditable)entity.Entity).CreatedAt = now;
((Auditable)entity.Entity).UpdatedAt = now;
}
((Auditable)entity.Entity).UpdatedAt = now;
}
}
I couldn't find any solution on the internet.
Update: I downgraded Microsoft.EntityFrameWorkCore from 7.0.0 to 6.6 and all related packages, then the migration was built successfully. So, it looks like a bug. I will try to find the issue on GitHub or create one.

Including a Model from different DbContext

I am not sure how to achieve the relation between 2 DbContexts. PurchaseOrderDbContext is a Code first approach & AgencyDbContext is an existing database. How can I include the "Division" from AgencyDbContext based on PurchaseOrder DivisionId?
To start off here is a very simplified version of my code.
Purchase Order Model
namespace Website.Models.PurchaseOrders
{
public class PurchaseOrder
{
public int ID { get; set; }
public DateTime OrderDate { get; set; }
public string Name { get; set; }
public int DivisionId { get; set; }
public int StatusID { get; set; }
public Agency.Division Division { get; set; }
}
}
Division Model (this is in a different DbContext)
namespace Website.Models.Agency
{
public class Division
{
public int DivisionId { get; set; }
public string DivisionName { get; set; }
public string DivisionShortName { get; set; }
public string DivisionAbbrev { get; set; }
public int? DivisionDirectorEmpId { get; set; }
}
}
Agency DbContext
namespace Website.Models.Agency
{
public class AgencyDbContext : DbContext
{
public Agency DbContext(DbContextOptions<AgencyDbContext> options) : base(options)
{
}
public virtual DbSet<Division> Division { get; set; }
public virtual DbSet<Section> Section { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}
PurchaseOrderDbContext
namespace Website.Models.PurchaseOrders
{
public class PurchaseOrderDbContext : DbContext
{
public PurchaseOrderDbContext(DbContextOptions<PurchaseOrderDbContext> options) : base(options)
{}
public DbSet<Status> Statuses { get; set; }
public DbSet<PurchaseOrder> PurchaseOrder { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}
I get an the error InvalidOperationException: Lambda expression used inside Include is not valid. This is referring to the Include extension on Division.
var purchaseOrder = _context.PurchaseOrder
.Include(p => p.Division)
.Include(p => p.Status)
.OrderByDescending(p => p.OrderDate);
Thank you in advance!
Probably the only way to resolve is to make a query to the first context for items you are looking for, and then populate Division property with entries from second context
public class PurchaseOrderService
{
private readonly PurchaseOrderDbContext purchaseOrderDbContext;
private readonly AgencyDbContext agencyDbContext;
public PurchaseOrderService(PurchaseOrderDbContext purchaseOrderDbContext,
AgencyDbContext agencyDbContext)
{
this.purchaseOrderDbContext = purchaseOrderDbContext;
this.agencyDbContext = agencyDbContext;
}
public PurchaseOrder Get(int id)
{
var purchaseOrder = purchaseOrderDbContext.PurchaseOrder.FirstOrDefault(x => x.ID == id);
if (purchaseOrder == null)
{
return null;
}
purchaseOrder.Division = agencyDbContext.Division.FirstOrDefault(x => x.DivisionId == purchaseOrder.DivisionId);
return purchaseOrder;
}
}

DbContext is not giving any data from database

I have two sets of codes. The first one doesn't give me the list of data but the second on does. Please see codes below:
First Code:
Model
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
DataConnection
public class DataConnection : DbContext
{
public DataConnection()
: base("DefaultConnection")
{
}
public DbSet<Student> Students { get; set; }
}
Interface
public interface IStudent
{
List<Student> StudentList();
void InsertStudent(Student student);
void UpdateStudent(Student student);
Student GetStudentById(int id);
void DeleteStudent(int id);
}
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
var studentList = (from s in _context.Students select s).ToList();
return studentList;
}
Second Code
Concrete
readonly DataConnection _context;
public StudentConcrete()
{
_context = new DataConnection();
}
public List<Student> StudentList()
{
SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var cmd = new SqlCommand("GetAllStudents", xxx);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return (from DataRow row in ds.Tables[0].Rows
select new Student()
{
Age = Convert.ToInt32(row["Age"]),
FirstName = row["FirstName"].ToString(),
Gender = row["Gender"].ToString(),
LastName = row["LastName"].ToString()
}).ToList();
}
else
{
return null;
}
}
I would like to get the data using the first code but I don't know where I get it wrong. My SP is just to get the students.
I suspected that maybe you are retrieving the records from another table somehow. Would you try to add Table attribute for Student entity.
using System.ComponentModel.DataAnnotations.Schema;
[Table("Students")]
public class Student
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}

I can't create a simple dataBase in EntityFramework Core

I'm a realy newbie in EntityFramework and Core.
I want to create a simple DataBase in EntityFramework Core 2.0. The project is a ConsoleApplication that I included it a Microsoft.AspNetCore.All by Nuget package. This is a code:
namespace TestEF
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";
var db = new SchoolContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connStr).Options);
db.Students.Add(
new Student()
{
LastName = "Miranda",
EnrollmentDate = DateTime.Now,
FirstMidName = "Guillermo"
});
db.SaveChanges();
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
}
}
I'm loggin into a intranet as username "gmiranda". When I run the project I get the following message error:
System.Data.SqlClient.SqlException occurred
HResult=0x80131904
Message=Cannot open database "SchoolDataBase" requested by the login. The login failed.
Login failed for user 'domain\gmiranda'.
What is I doing wrong ?
Thanks !
You should try this code:
class Program
{
static void Main(string[] args)
{
string connStr = "Data Source=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";
var db = new SchoolContext();
db.Students.Add(
new Student()
{
LastName = "Miranda",
EnrollmentDate = DateTime.Now,
FirstMidName = "Guillermo"
});
db.SaveChanges();
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true");
}
public DbSet<Student> Students { get; set; }
}
Then open Package Manager Console and use command Add-Migration FirstMigrarion.
Its add migration to your database with name FirsMigration.
Then use command Update-Database.
Then run your program.
Try use this tutorial: https://learn.microsoft.com/en-us/ef/core/get-started/full-dotnet/new-db

EntityFramework relations giving incorrect results - WebAPI does not accept {id}

I am building a WebAPI and I have populated my Database with 5 different Organizations, each organization has 3 different Contacts, each Contact has 3 phone numbers with EntityFramework.
But somehow it behaves in a weird way:
I get a complete list of Contacts and organizations
I get just a contact under an organization (GET -> api/organizations)
I get just one phone under a contact (GET -> api/contacts)
It does not accept parameter in the api routes such as: api/contacts/{id} or api/organizations{id}. It returns 404 code.
My questions:
1- Are the relation between models is wrong built and therefore I get just one sub-element instead the whole list?
2- Why does my routes do not accept parameters {id}?
These are my models:
**Organization:**
public class Organization {
public Guid Id { get; set; }
public DateTime dateCreated { get; set; }
public string organizationName { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
**Contact:**
public class Contact {
public Contact() { }
public Guid Id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
// Foreign Key for Organizations
public Guid OrganizationId { get; set; }
//Related Organization entity
[ForeignKey("OrganizationId")]
public Organization OrganizationData { get; set; }
}
**Phones:**
public class Phone {
public Guid Id { get; set; }
public string customName { get; set; }
public string phoneNumber { get; set; }
// Foreign Key for Contacts
public Guid ContactId { get; set; }
//Related Contact entity
[ForeignKey("ContactId")]
public Contact ContactData { get; set; }
}
These are my controllers:
**OrganizationsController:**
[Route("api/organizations")]
public class OrganizationsController : Controller
{
[HttpGet ("")]
public IActionResult Get()
{
var results = _repository.GetAllOrganizations();
return Ok(Mapper.Map<IEnumerable<Organization>>(results));
}
[HttpGet("")]
public IActionResult Get(Guid Id)
{
var organization = _repository.GetOrganizationById(Id);
return Ok(organization);
}
}
**ContactsController**
[Route("api/organization/{id}/contacts")]
public class ContactsController : Controller
{
[HttpGet("")]
public IActionResult Get(Guid Id)
{
var organization = _repository.GetOrganizationById(Id);
return Ok(organization.Contacts.ToList());
}
}
}
**AllContactsController**
[Route("api/contacts")]
public class AllController : Controller
{
[HttpGet("")]
public IActionResult Get()
{
var results = _repository.GetAllContacts();
return Ok(Mapper.Map<IEnumerable<Contact>>(results));
}
[HttpGet("/{id}")]
public IActionResult Get(Guid Id)
{
var contact = _repository.GetContactById(Id);
return Ok(contact);
}
EDIT: adding the repository:
public class ContactManagementRepository : IContactManagementRepository
{
private ContactManagementContext _context;
private ILogger<ContactManagementRepository> _logger;
public ContactManagementRepository(ContactManagementContext context, ILogger<ContactManagementRepository> logger)
{
_context = context;
_logger = logger;
}
public IEnumerable<Organization> GetAllOrganizations()
{
_logger.LogInformation("Getting All Organizations from the Database");
return _context.Organizations.ToList();
}
public IEnumerable<Contact> GetAllContacts()
{
_logger.LogInformation("Getting All Contacts from the Database");
return _context.Contacts.ToList();
}
public void AddOrganization(Organization organization)
{
_context.Add(organization);
}
public void AddContact(Guid id, Contact newContact)
{
var organization = GetOrganizationById(id);
if(organization != null)
{
organization.Contacts.Add(newContact);
_context.Contacts.Add(newContact);
}
}
public async Task<bool> SaveChangesAsync()
{
return (await _context.SaveChangesAsync()) > 0;
}
public Organization GetOrganizationById(Guid Id)
{
return _context.Organizations
.Include(c => c.Contacts)
.Where(c => c.Id == Id)
.FirstOrDefault();
}
public Contact GetContactById(Guid Id)
{
return _context.Contacts
.Include(c => c.Addresses)
.Include(c => c.Bankdatas)
.Include(c => c.Phones)
.Where(c => c.Id == Id)
.FirstOrDefault();
}
public void DeleteContact(Guid id)
{
var contact = GetContactById(id);
if (contact != null)
{
_context.Contacts.Remove(contact);
}
}
}
Try for OrganizationsController
[HttpGet("{id}")]
public IActionResult Get(Guid Id)
{
var organization = _repository.GetOrganizationById(Id);
return Ok(organization);
}
and try for AllController
[HttpGet("{id}")]
public IActionResult Get(Guid Id)
{
var contact = _repository.GetContactById(Id);
return Ok(contact);
}
Your models look good for me. Can you show your repositories?