An unknown output in ASP.NET Core API - asp.net-core-webapi

I use SQLite as a database. I have two entities as follows:
public class Topic
{
[Key]
public int Id { get; set; }
[Required]
[DataType(DataType.Text)]
[MaxLength(100)]
public string Name { get; set; }
public virtual IEnumerable<SubTopic> SubTopics { get; set; }
}
public class SubTopic
{
[Key]
public int Id { get; set; }
[Required]
[DataType(DataType.Text)]
[MaxLength(100)]
public string SubTopicname { get; set; }
[Required]
[DataType(DataType.Text)]
[MaxLength(100)]
public string Subject { get; set; }
[Required]
[DataType(DataType.Text)]
[MaxLength(300)]
public string ShortDescription { get; set; }
[Required]
[DataType(DataType.Text)]
public string Description { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Required]
[DataType(DataType.Text)]
public string Reference { get; set; }
[ForeignKey("Name")]
public virtual Topic Topic { get; set; }
}
The action for getting all topics:
public async Task<IActionResult> GetAllTopics()
{
var myTopics = await _myContext.Topics.ToListAsync();
return Ok(myTopics);
}
My Context is:
public class MyContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder option)
{
option.UseSqlite("Data Source=Database.db;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Topic>().ToTable("Topics");
modelBuilder.Entity<ImportantPost>().ToTable("ImportantPost");
modelBuilder.Entity<About>().ToTable("About");
modelBuilder.Entity<FeaturedPost>().ToTable("FeaturedPost");
modelBuilder.Entity<SubTopic>().ToTable("SubTopic");
}
public DbSet<Topic> Topics { get; set; }
public DbSet<ImportantPost> ImportantPosts {get; set;}
public DbSet<About> About { get; set; }
public DbSet<FeaturedPost> FeaturedPosts { get; set; }
public DbSet<SubTopic> SubTopic { get; set; }
}
When I try to get all topics using Swagger the output is:
My table is empty. My expected output is [] while it shows another thing.
I need an array in my output. This output causes problems in my Angular UI. How can I fix this?

I think something are wrong; response body s hould like this
{
id : 1,
name : "foo",
subTopics : []
}
check your code again or share it with us

This StackOverflow link helped me to solve my problem:
JsonSerializerOptions
I used this settings in service registration:
services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = null);

Related

Code First Model Definition

I have the following models,do I define it Ok?
User is the main Entity and can have 0..1 to * (zero /one to many relationship ) address.
2.User can have have 0..1 to 1 (one to one userPass )
This is the main table
public class User
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PhoneWork { get; set; }
public string WorkingAt { get; set; }
public virtual UserPass UserPass { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class ConfigModelDbContext : DbContext
{
public DbSet<User> User { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<UserPass> UserPasses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<User>()
.HasOptional(c => c.Addresses).WithRequired(addresses => new User());
modelBuilder.Entity<User>()
.HasOptional(c => c.UserPass).WithRequired(pass => new User());
}
}
Address Class
public class Address
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string UserAddress { get; set; }
}
Userpass class
public class UserPass
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
i also created classes same as above but can it create relationship directly on database table?
at first I offer you to use data annotation instead of fluent api always.
then correct AddressClass like below:
public class Address
{
[Key]
public int Id { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public string UserId { get; set; }
public string UserAddress { get; set; }
}
This will create Ralationship.
for more details please read Code First DataAnnotations

Table with foreign key of same entity type

Hi I've been searching around for like 40 minutes now trying to figure out how to do this and I'm not having any luck. I'm creating a forum app with ASP.NET. MVC5, and EF6. My app contains a Comment model; this is where I started running into problems. I want threads to be able to have comments(this was easy) and I also want comments to have comments(This is my problem).
Here is how my model is defined:
namespace Forum.Models
{
public class Comment
{
[Key]
public int Id {get; set;}
[DisplayFormat(DataFormatString = "{0:d/M/yyyy HH:mm:ss}",
ApplyFormatInEditMode = true)]
public DateTime TimeStamp { get; set; }
public string Content { get; set; }
public String UserId { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
[ForeignKey("ParentComment")]
public int ParentCommentId { get; set; }
public virtual Comment ParentComment { get; set; }
public int ThreadId { get; set; }
public virtual Thread Thread {get; set;}
}
}
This is the error I get when I try to update this table:
Cannot insert explicit value for identity column in table 'Comments' when IDENTITY_INSERT is set to OFF.
Any help would be greatly appreciated.
I agree with #Slauma, you need to change ParentCommentId to int? type. Also if you want to use ForeignKeyAttribute, you need to assign it to navagation property, like below:
public int? ParentCommentId { get; set; }
[ForeignKey("ParentCommentId")]
public virtual Comment ParentComment { get; set; }
Below is an example, I'm using fluent API to configure the relationships.
Coment Model class:
public class Comment
{
[Key][DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:d/M/yyyy HH:mm:ss}",ApplyFormatInEditMode = true)]
public DateTime TimeStamp { get; set; }
public string Content { get; set; }
public String UserId { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public int? ParentCommentId { get; set; }
public virtual Comment ParentComment { get; set; }
public int ThreadId { get; set; }
public virtual Thread Thread { get; set; }
}
DbContext class:
public class YourDbContext : DbContext
{
public DbSet<Comment> Comments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Comment>()
.HasOptional(c => c.ParentComment )
.WithMany(c => c.Comments)
.HasForeignKey(c => c.ParentCommentId );
}
}

EF6 MVC5 Setting a 1-1 Relationship

I have got my application up and running using Code first, I am trying to set a 1-1 relationship but when I update-database I get the error "SupplyPointId: Name: Each property name in a type must be unique. Property name 'SupplyPointId' is already defined."
I've tried removing the existing index constraint on SupplyPointAddress.SupplyPointId and that does not help. In the other table its the PK. Any comments really appreciated
public partial class SupplyPoint
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointId { get; set; }
public string SPID { get; set; }
public string SupplyPointName { get; set; }
public int SupplyPointTypeId { get; set; }
public DateTime SupplyPointEffectiveDateTime { get; set; }
public string GazateerRef { get; set; }
public virtual SupplyPointType SupplyPointType { get; set; }
//[ForeignKey("SupplyPointId")]
public virtual SupplyPointAddress SupplyPointAddress { get; set; }
}
public partial class SupplyPointAddress
{
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SupplyPointAddressId { get; set; }
public int SupplyPointId { get; set; }
public string D5001_FreeDescriptor { get; set; }
public string D5002_SubBuildingName { get; set; }
public string D5003_BuildingName { get; set; }
public string D5004_BuildingNumber { get; set; }
public string D5005_DependentThoroughfareName { get; set; }
public string D5006_DependentThoroughfareDescriptor { get; set; }
public string D5007_ThoroughfareName { get; set; }
public string D5008_ThoroughfareDescriptor { get; set; }
public string D5009_DoubleDependentLocality { get; set; }
public string D5010_DependentLocality { get; set; }
public string D5011_PostTown { get; set; }
public string D5012_County { get; set; }
public string D5013_Postcode { get; set; }
public virtual SupplyPoint SupplyPoint { get; set; }
}
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPoint> SupplyPoints { get; set; }
public System.Data.Entity.DbSet<AscendancyCF.Models.SupplyPointAddress> SupplyPointAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SupplyPointAddress>()
.HasOptional<SupplyPoint>(u => u.SupplyPoint)
.WithRequired(c => c.SupplyPointAddress).Map(p => p.MapKey("SupplyPointId"));
base.OnModelCreating(modelBuilder);
}
I moved the foreign key into SupplyPoint table so that the foreign key was being defined as SupplyPointAddressId in SupplyPoint. This worked and allows me to do SupplyPoint.SupplyPointAddress in resultant model
Since you're testing with a real DB. Use some of the
Database Initialization Strategies in Code-First:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
(Excerpt from this site)
It is pretty self explanatory.
If there's already a DB created, it just DROPs it.
Happy coding!

Entity Framework WebApi Circular dependency serialization error

I think, I've read everything about this error and I tried everything. Here are my models:
Main:
public class Trip
{
public int TripId { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string Country { get; set; }
public float BasicPrice { get; set; }
public virtual ICollection<ApartmentType> ApartmentType { get; set; }
public virtual ICollection<TransportMethod> TransportMethod { get; set; }
public virtual ICollection<FeedingType> FeedingType { get; set; }
}
ApartmentType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
FeedingType:
public class FeedingType
{
public int FeedingTypeId { get; set; }
public int TripId { get; set; }
public string Description { get; set; }
public float Price { get; set; }
}
TransportType:
public class TransportMethod
{
public int TransportMethodId { get; set; }
public int TripId { get; set; }
public string Name { get; set; }
public float Price { get; set; }
}
When serializng the Trip entity I get a circular dependency error. Things i tried:
Disable lazy loading in DbContext.
Adding
json.SerializerSettings.PreserveReferencesHandling=Newtonsoft.Json.PreserveReferencesHandling.All; to GLobal.asax
Adding a decorator [IgnoreDataMember] to TripId in every child entity.
Mapping this entity to a ViewModel which doesn't contain the ICollection members. - This worked ok, but at some point I will want to get those lists to the client.
I really don't know what's going on. What am I missing? I really can't spot any circular dependency.
Have you tried adding the [JsonIgnore] attribute to the TripId to the children entities?
http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm
or setting
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

Model collections of the same class held by several other classes

How do I model the following using Castle ActiveRecord?
I have two classes, Customer and Task.
I would like to reuse a third class, Note, stored in a Collection in each of the Customer and Task classes.
public class Note
{
public int ID { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
public class Customer
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
public class Task
{
public int ID { get; set; }
public IList<Note> Notes { get; set; }
}
I would then like to be able to pass the Notes collection to a Gridview, Listview or Repeater in the relevant ASP.Net page for the Customer or Task classes.
I think what you need is to implement a type hierarchy. You can read about it here.
We settled on the following pattern:
[ActiveRecord]
public class Note
{
[PrimaryKey]
public int ID { get; set; }
[Property]
public string Subject { get; set; }
[Property]
public string Body { get; set; }
[BelongsTo]
public Customer Customer { get; set; }
[BelongsTo]
public Customer Task{ get; set; }
}
[ActiveRecord]
public class Customer
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}
[ActiveRecord]
public class Task
{
[PrimaryKey]
public int ID { get; set; }
[HasMany]
public IList<Note> Notes { get; set; }
}

Resources